zip

fun <T1, T2, R> Flow<T1>.zip(other: Flow<T2>, transform: suspend (T1, T2) -> R): Flow<R>

Zips values from the current flow (this) with other flow using provided transform function applied to each pair of values. The resulting flow completes as soon as one of the flows completes and cancel is called on the remaining flow.

It can be demonstrated with the following example:

val flow = flowOf(1, 2, 3).onEach { delay(10) }
val flow2 = flowOf("a", "b", "c", "d").onEach { delay(15) }
flow.zip(flow2) { i, s -> i.toString() + s }.collect {
println(it) // Will print "1a 2b 3c"
}

Buffering

The upstream flow is collected sequentially in the same coroutine without any buffering, while the other flow is collected concurrently as if buffer(0) is used. See documentation in the buffer operator for explanation. You can use additional calls to the buffer operator as needed for more concurrency.

Sources

common source
Link copied to clipboard