【问题标题】:Kotlin coroutines barrier: Wait for all coroutines to finishKotlin 协程屏障:等待所有协程完成
【发布时间】:2019-10-24 14:11:20
【问题描述】:

我需要在一个 for 循环中启动许多协程,并在所有任务完成后在主线程中获取回调。

最好的方法是什么?

//Main thread
fun foo(){
    messageRepo.getMessages().forEach {message->
       GlobalScope.launch {
            doHardWork(message)
       }
    }
   // here I need some callback to the Main thread that all work is done.
}

并且在 CoroutineScope 中没有迭代消息的变体。迭代必须在主线程中完成。

【问题讨论】:

    标签: kotlin coroutine kotlin-coroutines


    【解决方案1】:

    您可以等到所有任务都使用awaitAll 完成,然后在主线程中使用withContext 执行您的回调

    fun foo() {
        viewModelScope.launch {
            messageRepo.getMessages().map { message ->
                viewModelScope.async(Dispatchers.IO) {
                    doHardWork(message)
                }
            }.awaitAll()
            withContext(Dispatchers.Main) {
                // here I need some callback that all work is done.
            }
        }
    }
    

    【讨论】:

    • 感谢您的回答。但是在你的代码中迭代不在主线程中。
    • @DmitriyPuchkov 抱歉,我错过了这一点。现在已经修复了
    • 请更新您对 async(Dispatchers.IO) 的回答,因为万一 async(Dispatchers.Main) doHardWork 在主线程中执行
    • @DmitriyPuchkov 当然。另一个误解:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 2021-10-27
    • 2014-12-16
    • 2021-03-30
    • 1970-01-01
    • 2022-01-18
    相关资源
    最近更新 更多