Is it possible to observe changes in MutabeState from ViewModel? Obviously, all changes made to MutableState will cause re-composition in Composable. But is it possible to observe changes made by composable to MutableState from ViewModel?
In example: let's say we have input text from user which value is stored in MutableState in ViewModel. When user enters, say, 6 characters, we want to trigger an action in ViewModel. Or verify input on every character. We can do this using MutableStateFlow or Channel and collecting values in ViewModel's init. But is it possible using only MutableState? Or what is the best way to achieve this behavior?
You will not be able to observe a MutableState from a ViewModel as it is coming from the package androidx.compose.runtime.mutableStateOf and not designed for this.
The positive point is that usage with compose is very simple, only write in the field will update only the necessary part of the UI. There's not postValue() neither .observe() function
The alternative way you have to fix your problem is to use a StateFlow, which is coming from the package kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.onEach
// ViewModel
private val _testState = MutableStateFlow<Int>(2)
val testState: StateFlow<Int> get() = _testState.asStateFlow()
init {
testState.onEach {
if (it == 5) {
// caught
}
}
}
fun someFunc() {
_testState.update { 5 }
}
You can find inspiration to this repository : https://github.com/android/nowinandroid/blob/main/feature/foryou/src/main/kotlin/com/google/samples/apps/nowinandroid/feature/foryou/ForYouViewModel.kt#L86
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With