我需要在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中没有迭代消息的变体。迭代必须在主线程中完成。
发布于 2019-10-24 14:36:03
您可以等到所有任务都用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.
}
}
}https://stackoverflow.com/questions/58543249
复制相似问题