启动两个协程并等待单个结果



我想知道是否有其他方法可以启动两个协程并从更快的协程返回结果。我已经使用channelFlow完成了它,但我认为可能有一些其他的解决方案。

suspend fun execute(): Result {
return channelFlow {
listOf(
coroutineScope.async { send(firstCourotine()) },
coroutineScope.async { send(secondCourotine()) }
).awaitAll()
}.first().also { cancel() }
}

您可以使用select表达式,使execute成为CoroutineScope扩展函数:

suspend fun CoroutineScope.execute(): Result {
val list = listOf(
async { firstCourotine() },
async { secondCourotine() }
)
return select {
list.forEach {
it.onAwait { answer ->
answer
}
}
}
}

您应该在可以取消的范围内调用execute,以便在收到结果后立即停止其所有活动的协程:

...
val scope = CoroutineScope(Dispatchers.Default)
val result = scope.async {
val res = execute()
coroutineContext.cancelChildren()
res
}.await()
//Do something with 'result' here
...

注:select表达处于实验状态。

你可以在这里找到select表达式的官方文档。

最新更新