是否有C#的Task.WhenAll的Kotlin等效项?
我想出了下面的代码,但是我想知道是否有可能编写whenAll
使其仅挂起一次。
fun main(args: Array<String>) = runBlocking {
println("Start")
val serviceA = KotlinServiceA()
val serviceB = KotlinServiceB()
val deferredA = async(CommonPool) { serviceA.operationA() }
val deferredB = async(CommonPool) { serviceB.operationB() }
var tasks = arrayOf(deferredA, deferredB)
tasks.whenAll()
println("End")
}
suspend fun Array<Deferred<Unit>>.whenAll() : Unit {
for (task in this) {
task.await()
}
}
答案 0 :(得分:5)
有一个awaitAll()
函数可以完成这项工作。
val deferredArray: Array<Deferred<Unit>> = arrayOf()
val awaitAllArray = awaitAll(*deferredArray)
如果您使用Collection
,则可以使用awaitAll()
扩展功能
val deferredList: List<Deferred<Unit>> = listOf()
val awaitAllList = deferredList.awaitAll()