Reputation: 907
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.
Upvotes: 7
Views: 9340
Reputation: 30585
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")
}
Upvotes: 10
Reputation: 960
You can use something like this:
fun <T> Flow<T>.merge(otherFlow: Flow<T>) = flow {
[email protected] { value ->
emit(value)
}
otherFlow.collect { value ->
emit(value)
}
}
Note that the resulting flow will only finish when both flows are completed/canceled.
Usage:
someFlow.merge(stateFlow).collect {
println(it)
}
Upvotes: 0