Kotlin协程障碍:等待所有协程完成

时间:2019-10-24 14:11:20

标签: kotlin coroutine kotlin-coroutines

我需要在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中没有迭代消息的变体。迭代必须在主线程中完成。

1 个答案:

答案 0 :(得分:2)

您可以等到$users = DB::table('users') ->offset(10) ->limit(5) ->get(); 完成所有任务,然后再使用awaitAll在主线程中执行回调。

withContext
相关问题