Danish Ansari
11/02/2022, 11:12 AMStateFlow
to be specific
I have MutableStateFlow<UiState>
and corresponding StateFlow<UiState>
defined in my viewmodel
class MainViewModel:ViewModel() {
private val mutableUiState = MutableStateFlow(UiState())
val uiState = mutableUiState.asStateFlow()
// ...
}
And my UiState is roughly defined like this
data class UiState(
val propertyA: Int = 0,
val propertyB: Boolean = false
) {
private var mutableProperty: Int = 0
val derivedProperty: Boolean
get() = mutableProperty % 2 == 0
fun someMethod(newProperty: Int) {
mutableProperty = newProperty
// some extra logic goes here
}
}
Now the doubt is that in my viewmodel I’m calling mutableUiState.someMethod(someInteger)
but I think uiState
is not getting updated because I have used uiState.derivedProperty
at some place in UI in compose and the UI is not updating.
Someone care to help what I’m doing wrong? Thankskrzysztof
11/02/2022, 12:39 PMMutableStateFlow
is not aware of internal changes in your UiState class, hence no new emits of the valuekrzysztof
11/02/2022, 12:44 PM.value
of MutableStateFlow.
So in your ViewModel, you should do something like
mutableUiState.value = mutableUiState.someMethod(/*...*/)
where .someMethod
should return a new instance of your UiState
class, because that’s the type you declared to be emittedkrzysztof
11/02/2022, 12:45 PMsomeMethod
could return copy()
of your classKevin Del Castillo
11/02/2022, 1:02 PMvalue
or using the update
function which should always return a new instance and not do any internal mutation, you'll often see the latter combined with the copy
method of data classes.Danish Ansari
11/03/2022, 6:08 AMDanish Ansari
11/03/2022, 6:09 AM