gpt4 book ai didi

kotlin - 如何 'zip'两个或更多协程 channel ?

转载 作者:行者123 更新时间:2023-12-02 12:52:55 27 4
gpt4 key购买 nike

因此,在RxJava中,我们可以简单地执行以下操作:

Observable.zip(someObservable, anotherObservable, BiFunction { a, b -> //do something }.subscribe { // do something }

我们如何使用Kotlin Coroutine Channels做同样的事情?

最佳答案

不是理想的解决方案,但似乎可行

@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()
}

更新

另外,不推荐使用运算符 zip

关于kotlin - 如何 'zip'两个或更多协程 channel ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56948696/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com