我需要填写数据库中的对象列表。在将值传递给项目之前,我希望所有项目都完成。这里是否有任何调用await()让每个项目等待的简短方法。我想编写干净的代码,可能是一些设计模式或技巧?
for (x in 0..10) {
launch {
withContext(Dispatchers.IO){
list.add(repository.getLastGame(x) ?: MutableLiveData<Task>(Task(cabinId = x)))
}
}
}
items.value = list
coroutineScope { // limits the scope of concurrency
(0..10).map { // is a shorter way to write IntRange(0, 10)
async(Dispatchers.IO) { // async means "concurrently", context goes here
list.add(repository.getLastGame(x) ?: MutableLiveData<Task>(Task(cabinId = x)))
}
}.awaitAll() // waits all of them
} // if any task crashes -- this scope ends with exception
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)