gpt4 book ai didi

kotlin - 相当于 Kotlin Deferred 的 anyOf

转载 作者:IT老高 更新时间:2023-10-28 13:36:18 27 4
gpt4 key购买 nike

协程 async返回 Deferred<T>还有延迟执行的例子和 await 的用法。

但是,我们怎么能等待 Deffered 中的任何一个?要完成的实例?

简而言之

  // whats the equivalent of CompletableFuture.anyOf(...)?
// is this how we do it? if so how costly is this?
select<Unit> {
deffered1.onAwait {}
deffered2.onAwait {}
}

最佳答案

可能不是最安全的做事方式,但这样的事情应该可行:

inline suspend fun <T> Iterable<Deferred<T>>.awaitAny(): T {
var completed: T? = null
forEachIndexed { index, deferred ->
deferred.invokeOnCompletion {
completed = deferred.getCompleted()
forEachIndexed { index2, deferred2 ->
if (index != index2) {
deferred2.cancel(it)
}
}
}
}
forEach {
try {
it.await()
} catch (ignored: JobCancellationException) {
// ignore
}
}
return completed!!
}

证明:以下打印 1000

launch(CommonPool) {
// 10 - 1 second(s)
val deferredInts = List(10, {
val delayMs = (10 - it) * 1000
async(CommonPool) {
delay(delayMs)
delayMs
}
})
val first = deferredInts.awaitAny()
println(first)
}

关于kotlin - 相当于 Kotlin Deferred 的 anyOf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49553213/

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