Kotlin coroutines barrier:等待所有协程完成

Kotlin coroutines barrier: Wait for all coroutines to finish

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

您可以使用 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.
        }
    }
}