Nur*_*lov 8 android kotlin-coroutines
我需要从数据库填充对象列表。在将值传递给 itemes 之前,我希望它们都完成。这里有任何简短的方法为每个要等待的项目调用 await()。我想编写干净的代码,可能是某种设计模式或技巧?
for (x in 0..10) {
launch {
withContext(Dispatchers.IO){
list.add(repository.getLastGame(x) ?: MutableLiveData<Task>(Task(cabinId = x)))
}
}
}
items.value = list
Run Code Online (Sandbox Code Playgroud)
Rom*_*rov 23
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4263 次 |
| 最近记录: |