0

I’m trying to make my methods reactive to update the view in Compose. How to do it properly?

interface Foo{
  val a: Int
  fun bar(): Int
  fun foo(): MutableStateFlow<Int> = MutableStateFlow(bar() * a)
}

//@Composable
val foo by fooImpl.foo().collectAsState()

P.S. Currently I made a hack: empty usage a variable a participated in calculations. But it’s not good.

val a = fooImpl.collectAsState()
a
Psijic
  • 743
  • 7
  • 20
  • Why do it at all? – vitidev Oct 08 '22 at 16:00
  • Because of calculations in models. It's not always done on a server side. – Psijic Oct 09 '22 at 08:36
  • I still don't understand your problem. There are many different ways run something. Why is it necessary `fun ...: MutableStateFlow`? I don't know situations where this might be needed instead of other approaches – vitidev Oct 09 '22 at 10:03
  • Ok, the simple question is: how to make an observable function? – Psijic Oct 09 '22 at 10:45
  • I suppose, the best but longest way is to observe all variables participated in the method and then provide a final observable variable. But it doesn't work in interfaces. – Psijic Oct 09 '22 at 11:08

1 Answers1

0

One way to do it - subscribe to all variables used in a method.

var a = MutableStateFlow(0)
fun bar() = a.value +1
fun chad() = 42
fun foo() = bar() * chad()

val foo: Flow
  get() = a.map { (it + 1) * chad() }

fun useFoo() = runBlocking {
    withContext {
        foo.collect {
            something(it)
        }
    }
}
Psijic
  • 743
  • 7
  • 20