Combine two kotlin flows into a single flow that emits the latest value from the two original flows?
If we have two flows defined like this:
val someflow = flow {
emit("something")
}
and another flow defined like:
val stateFlow = MutableStateFlow("some value")
Is it possible to combine the two flows into a single flow that just emits the last value emitted by either someflow
or stateFlow
?
The idea is that stateFlow
might emit a value at some point in the future, but until that happens I just want whatever value someflow
last emitted. In the "combined" flow, I would like to just take the first value emitted by someflow
but then be able to observe the rest of the updates on stateFlow
.
It seems like this might be accomplished with a combine function, but I just want to emit the latest emitted value between the two flows, I don't care about what the last value of one flow was.
There is a flattenMerge
function, which executes flows as a single flow, it might be what you need. For example:
val numbersFlow = flowOf("1", "2", "3", "4").onEach { delay(1000) }
val lettersFlow = flowOf("A", "B", "C").onEach { delay(2000) }
flowOf(numbersFlow, lettersFlow).flattenMerge().collect {
println("Result $it")
}
Prints:
Result 1
Result A
Result 2
Result 3
Result B
Result 4
Result C
So for your case it would look something like:
flowOf(someFlow, stateFlow).flattenMerge().collect {
println("Result $it")
}