But I don't want to observe the values when one fl...
# coroutines
f
But I don't want to observe the values when one flow processed the latest value but the other hasn't
f
You can use
zip
on flow A and B which will emit when both flow A and flow B emit. https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/zip.html
e
if you emit on A then B, the zipped flow may emit multiple times, with new a value and old b value before both new values
if you need to guarantee that the a and b values are always observed in sync, they need to be sourced from the same flow
t
I think that would be true for
combine
but zip is only once each flow has a new value. With zip if flow A emitted
a
and flow B emitted
1,2,3,4,5
and zip combined the values as strings, only
a1
would emit downstream,
combine
would do
a1,a2,a3,a4,a5
e
oh right
f
Kinda weird there is no standard solution here. This issue should frequently occur in many use cases. For example updating UI state from flows like in many Android code samples in their official guide
It seems like official docs pretend this problem doesn't exist
f
what's wrong with zip?
f
What @ephemient pointed out above
f
he was talking about
combine
, not
zip
if you check the link I shared above you will see that
zip
emits when both flows emit. If one flow keeps emitting the zipped flow won't emit until the other flow has a new value
f
Ok, zip works as long as both flows are guaranteed to emit the same number of times
It's kinda brittle though
f
well, that's how it's meant to work, it's not brittle, it works just as described. If you need some different behaviour then you may need to construct your own operator
t
Or structure your flow(s) differently
f
The only way to do it in a non brittle way I can come up with is propagate the input event Id all the way down the pipeline
But that's awkward
f
if you share some more details on what your requirements are we may be able to point you in the right direction, but based on your original message
zip
is the best fit
f
zip will probably work in my specific case but the issue comes up often. Basically when you use flows as a reactive graph
Are flows not meant to be used as a reactive graph? The Android official docs certainly show flows used like that.
f
yes, you can use flows. Maybe, if you want to use this for a UI flow, you could consider a data class to represent your UI so you don't have to zip the flows, whenever any of them emit you update your data class based on the information emitted by the flow and push that to the UI. When the other flow emits you update the state again. Unless the 2 flows are in some way connected so that you have to aggregate the data from one and the other to build the UI state, having them separate would simplify your logic