0

I have view model like this:

class SimpleViewModel : ViewModel() {
    private val _state = MutableStateFlow(false)
    val state: StateFlow<Boolean> = _state
}

How can I collect this state's values and call methods from another class like this:

class AnotherClass {
    fun doWhenViewModelStateUpdateToTrue()
    fun doWhenViewModelStateUpdateToFalse()
}
sss sss
  • 154
  • 6

1 Answers1

0

Your other class needs a reference to the state flow and to a CoroutineScope to run the collection in.

The CoroutineScope should have a lifecycle matching that of this class. So if it's a class you create in an Activity, for example, you would pass lifecycleScope.

class AnotherClass(
    private val coroutineScope: CoroutineScope,
    private val flowToCollect: Flow<Boolean>
) {
    init {
        coroutineScope.launch {
            flowToCollect.collect {
                if (it) doWhenViewModelStateUpdateToTrue() 
                else doWhenViewModelStateUpdateToFalse()
            }
        }
    }

    fun doWhenViewModelStateUpdateToTrue() {
        //...
    }

    fun doWhenViewModelStateUpdateToFalse() {
        //...
    }
}
Tenfour04
  • 83,111
  • 11
  • 94
  • 154