Reputation: 13668
So in RxJava, we could simply do:
Observable.zip(someObservable, anotherObservable, BiFunction { a, b -> //do something }.subscribe { // do something }
How do we do the same thing with Kotlin Coroutine Channels?
Upvotes: 2
Views: 1734
Reputation: 8432
not ideal solution but it seems to work
@ExperimentalCoroutinesApi
private fun <T, R> CoroutineScope.zipChannels(
channel1: ReceiveChannel<T>,
channel2: ReceiveChannel<T>,
zip: (T, T) -> R
): ReceiveChannel<R> = produce {
val iterator1 = channel1.iterator()
val iterator2 = channel2.iterator()
while (iterator1.hasNext() && iterator2.hasNext()) {
val value1 = iterator1.next()
val value2 = iterator2.next()
send(zip(value1, value2))
}
channel1.cancel()
channel2.cancel()
close()
}
Update
Also, there is a deprecated operator zip
Upvotes: 1