协程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 - anyOf相当于Kotlin的递延,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49553213/

10-10 18:44