【问题标题】:Launch two coroutines and wait for single result启动两个协程并等待单个结果
【发布时间】:2021-02-09 11:53:26
【问题描述】:

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

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

【问题讨论】:

    标签: kotlin kotlin-coroutines


    【解决方案1】:

    您可以为此使用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表达式官方文档here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-15
      • 1970-01-01
      • 2016-11-13
      • 2020-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多