Kotlin Flow How to combine two flows and only emit the result when the first flow sends element

Viewed 2671

There are two flows: FlowA and FlowB.

I want to combine them and get the latest element from FlowA and the latest element from FlowB only when FlowA emits an element. It's like combining FlowA and FlowB but only triggers the combined flow when FlowA emits an element.

1 Answers

If flowA doesn't contain repeated elements, or if you're ok to "not trigger" on repeated elements of A, you could achieve what you want with zip and distinctUntilChangedBy like this:

val flowA = flowOf("a", "b", "c")
val flowB = flowOf(1, 2, 3)

val resultFlow = flowA.zip(flowB)
                      .distinctUntilChangedBy { (a, _) -> a }
                      .map { (a, b) -> TODO("combine a and b") }

Another option is making a StateFlow out of B and accessing the latest value when you need it (but it requires a scope to collect B in the state, so it makes this code half hot):

val flowA = flowOf("a", "b", "c")
val flowB = flowOf(1, 2, 3)

val stateB = flowB.stateIn(someScope)
val resultFlow = flowA.map { a -> 
    val b = stateB.value
    TODO("combine a and b")
}
Related