vac*_*ach 10 coroutine kotlin completable-future
Coroutine async
返回Deferred<T>
,有懒惰执行和等待用法的例子.
但是,我们如何等待任何一个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 {}
}
Run Code Online (Sandbox Code Playgroud)
可能不是最安全的做事方式,但这样的事情应该有效:
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!!
}
Run Code Online (Sandbox Code Playgroud)
证明:下面打印 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)
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
453 次 |
最近记录: |