Can anybody explain me why do sequenced setting va...
# coroutines
i
Can anybody explain me why do sequenced setting value in MutableStateFlow doesn’t emit until last value set? there is simplified example of what i do in my app in thread. i try to collect combined value from state flow, and emits are sequenced (lines 25, 26)
Sorry , i didn’t embed line numbers in screenshot
Copy code
25.        state.value = "next"
26.        state.value = Date()
when i do like i show at screenshot i get next output
Copy code
each: Sun Jan 09 12:16:15 MSK 2022
each: Sun Jan 09 12:16:15 MSK 2022
Thu Jan 01 03:00:00 MSK 1970: start
Sun Jan 09 12:16:15 MSK 2022: start
I got default values (start and date0) and then last emitted date
when i flip lines 25 and 26 i got
Copy code
each: next
each: next
Thu Jan 01 03:00:00 MSK 1970: start
Thu Jan 01 03:00:00 MSK 1970: next
opposite situation, date not emitted, but string does
looks like backpressure problem, but how can i pass backpressure strategy into state flow?
onEach
call shows that first value just not emitted
i tried many ways =
state.value =
,
state.updateAndGet
,
state.emit
,
state.tryEmit
but result alwas the same
j
State flow values are conflated. State flows are supposed to represent a state for which you only care about the latest value. You would be relying on a race if you relied on getting all change events
Also note that here you're in a multithreaded environnement, so you might have a chance by relying on a race. If you weren't, you would be guaranteed to miss the first value assignment, because setting the value of the flow is not a suspending operation, so other coroutines don't have a chance to run between the 2 assignments
i
Is there any way in coroutines api to do what am i want? Use single source of sequenced values, and filter it by any rule (without worry about values misssing)
Looks like StateFlow doesn’t RxJava subject equivalent at all
j
Maybe look into
SharedFlow
instead. They are for representing more general hot flows like this. State flow is a special case of it, optimized for conflated state.
👍 1
i
Thanks, looks like i did the thing