如何在 for 循环中启动 10 个协程并等待它们全部完成?
how to launch 10 coroutines in for loop and wait until all of them finish?
我需要从数据库中填写对象列表。在将价值传递给项目之前,我希望所有项目都完成。这里是否有为每个要等待的项目调用 await() 的任何简短方法。我想编写干净的代码,可能是某种设计模式或技巧?
for (x in 0..10) {
launch {
withContext(Dispatchers.IO){
list.add(repository.getLastGame(x) ?: MutableLiveData<Task>(Task(cabinId = x)))
}
}
}
items.value = list
IntRange( 0, 10 ).map {
async {
// Logic
}
}.forEach {
it.await()
}
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
这是一个与其他示例类似的示例,用于 firestore 快照。
scope.launch {
val annualReports = snapshots.map { snapshot ->
return@map async {
AnnualReport(
year = snapshot.id,
reports = getTransactionReportsForYear(snapshot.id) // This is a suspended function
)
}
}.awaitAll()
}
Returns:
listOf(AnnualReport(...), AnnualReport(...))
我需要从数据库中填写对象列表。在将价值传递给项目之前,我希望所有项目都完成。这里是否有为每个要等待的项目调用 await() 的任何简短方法。我想编写干净的代码,可能是某种设计模式或技巧?
for (x in 0..10) {
launch {
withContext(Dispatchers.IO){
list.add(repository.getLastGame(x) ?: MutableLiveData<Task>(Task(cabinId = x)))
}
}
}
items.value = list
IntRange( 0, 10 ).map {
async {
// Logic
}
}.forEach {
it.await()
}
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
这是一个与其他示例类似的示例,用于 firestore 快照。
scope.launch {
val annualReports = snapshots.map { snapshot ->
return@map async {
AnnualReport(
year = snapshot.id,
reports = getTransactionReportsForYear(snapshot.id) // This is a suspended function
)
}
}.awaitAll()
}
Returns:
listOf(AnnualReport(...), AnnualReport(...))