Hi I have one small doubt about flows: `StateFlow`...
# android
d
Hi I have one small doubt about flows:
StateFlow
to be specific I have
MutableStateFlow<UiState>
and corresponding
StateFlow<UiState>
defined in my viewmodel
Copy code
class MainViewModel:ViewModel() {
    private val mutableUiState = MutableStateFlow(UiState())
    val uiState = mutableUiState.asStateFlow()
    // ...
}
And my UiState is roughly defined like this
Copy code
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? Thanks
k
You should ask this in #flow But main problem here is that
MutableStateFlow
is not aware of internal changes in your UiState class, hence no new emits of the value
👍 1
you trigger new emit by assigning new value to
.value
of MutableStateFlow. So in your ViewModel, you should do something like
Copy code
mutableUiState.value = mutableUiState.someMethod(/*...*/)
where
.someMethod
should return a new instance of your
UiState
class, because that’s the type you declared to be emitted
👍 1
so your
someMethod
could return
copy()
of your class
👍 1
k
Krzysztof already answered your question, just to add my two cents, the changes you made to your private var in your UI state are considered internal mutability, changes made in that way won't emit a new value in your Flow, you have to manually update it assigning a new
value
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.
👍 1
d
Thanks @Kevin Del Castillo and @krzysztof That was a good explanation
Sure I’ll post it in #flow next time, if I have such query