如何在for循环中启动10个协程并等待它们全部完成?

时间:2019-04-27 05:04:00

标签: android kotlin-coroutines

我需要填写数据库中的对象列表。在将价值传递给项目之前,我希望所有项目都完成。这是调用每个项目要等待的await()的任何简短方法。我想编写干净的代码,可能是一些设计模式或技巧吗?

    for (x in 0..10) {
        launch {
            withContext(Dispatchers.IO){
                list.add(repository.getLastGame(x) ?: MutableLiveData<Task>(Task(cabinId = x)))
            }

        }

    }
    items.value = list

3 个答案:

答案 0 :(得分:2)

IntRange( 0, 10 ).map {
    async {
       // Logic
    }
}.forEach {
    it.await()
}

答案 1 :(得分:1)

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

答案 2 :(得分:1)

以下是与其他示例类似的示例,用于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()
}

返回:

listOf(AnnualReport(...), AnnualReport(...))