hey it seems flow does not have zip operator which...
# flow
m
hey it seems flow does not have zip operator which would take more than one argument
Copy code
.zip(Iterable<Flow>)
are there plans to add it?
c
What would it take as the transform lambda?
suspend (List<Any>) -> R
?
m
I would use same concept as for combine
Copy code
public inline fun <reified T, R> combine(
    vararg flows: Flow<T>,
    crossinline transform: suspend (Array<T>) -> R)
c
If you're happy with
combine
(they all must have a common super type), then you can just use it
e
zip and combine do different things, you can't trivially switch between them
m
@CLOVIS ☝️
zip waits for all flows to complete and then emit result, combine emits multiple results
e
this is not very efficient but should work:
Copy code
fun <T> Flow<T>.zip(others: Iterable<Flow<T>>): Flow<List<T>> =
    others.fold(map { listOf(it) }) { acc, flow -> acc.zip(flow, List<T>::plus) }
m
thx, but it's still not the same as rxjava counterpart where all zip tasks are executed at the same time
e
what do you mean, they are executed in parallel
m
sorry, you right I've understood that it will work in pairs flow0 + flow1 = result1 result1 + flow2 = result2 and so on, but I was mistaken, again thx for help
e
the
fold
sets up all the
zip
operations before anything is collected. once collecting starts, it'll pull from all of them. the big inefficiency is that constructing lists by
+
is O(N^2)
you can avoid that with a more complex implementation like
Copy code
fun <T> Iterable<Flow<T>>.zip(): Flow<List<T>> = flow {
    coroutineScope {
        val job = Job(coroutineContext.job)
        val channels = map { it.buffer(Channel.RENDEZVOUS).produceIn(this + job) }
        try {
            while (true) emit(channels.map { it.receiveCatching().onClosed { return@coroutineScope }.getOrThrow() })
        } finally {
            job.cancel()
        }
    }
}
but I have a hard time coming up with scenarios where you'd use
zip
on a wide enough collection of flows for it to really matter
m
you right, I hope someday this could be added on language level
e
I am not sure what you mean by that. Flows are not a language feature, they are a library construct