https://kotlinlang.org logo
#coroutines
Title
# coroutines
i

Ink

03/22/2024, 10:46 AM
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

CLOVIS

03/22/2024, 10:57 AM
snapshotFlow
doesn't emit when the same value is emitted multiple times: https://developer.android.com/jetpack/compose/side-effects#snapshotFlow
i

Ink

03/22/2024, 10:58 AM
ahh, ok should I use flow?
c

CLOVIS

03/22/2024, 10:58 AM
It depends on what you want to do. Why are you mutating the variable to the same value as previously?
z

Zach Klippenstein (he/him) [MOD]

03/22/2024, 2:16 PM
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
3 Views