Kotlin等效于C#Task.WhenAll

时间:2018-10-14 05:57:33

标签: kotlin coroutine

是否有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()
    }
}

1 个答案:

答案 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()