Hi, How I can collect value when my flow emit the ...
# coroutines
i
Hi, How I can collect value when my flow emit the same value? Now when I emit Option.Default, println doesn't invoke
var option: Option by mutableStateOf(Option.Default)
fun optionsFlow(): Flow<Option> = snapshotFlow { option }
option = Option.Default
launch{
state.optionsFlow().collectLatest{
println(it)
}
}
c
snapshotFlow
doesn't emit when the same value is emitted multiple times: https://developer.android.com/jetpack/compose/side-effects#snapshotFlow
i
ahh, ok should I use flow?
c
It depends on what you want to do. Why are you mutating the variable to the same value as previously?
z
There are two things going on here: 1. mutableStateOf will ignore value updates with equivalent values by default. 2. snapshotFlow won’t emit duplicate values either, as previously mentioned 1 can be changed by passing a mutation policy to mutableStateOf, but 2 is hard-coded.
This is a high-level property of “state” with a lowercase s. Two states that have the value are the same state. “Changing” a state from one value to the same value isn’t a state change event because the state hasn’t changed.
1
If you want more direct control of the flow you could consider MutableSharedFlow, but then be careful not to emit directly from the composition (use a SideEffect).
❤️ 1