Run two Kotlin coroutines inside coroutine in parallel

ぃ、小莉子 提交于 2020-06-27 09:10:08

问题


I have two suspend functions:

suspend fun sendData() : Boolean 

suspend fun awaitAcknowledge() : Boolean

and I want to wrap them in a third suspend function in which they should be executed in parallel and I want to calculate the final result by having both return values:

suspend fun sendDataAndAwaitAcknowledge() : Boolean {
    // TODO execute both in parallel and compare both results
}

However, if I write it like that,

suspend fun sendDataAndAwaitAcknowledge() : Boolean {
    val sendResult = sendData()
    val receiveAck = awaitAcknowledge()
}

the functions will be executed in a serial order, which will not work in my case.

Coming from RxJava, I would like to achieve something like the zip operator:

Single.zip(awaitAcknowledge(), sendData(), {receiveAck, sendResult -> ...})

How can I do this with Coroutines?


回答1:


You can use awaitAll for that purpose:

import kotlinx.coroutines.*

suspend fun sendDataAndAwaitAcknowledge() = coroutineScope {
    awaitAll(async {
        awaitAcknowledge()
    }, async {
        sendData()
    })
}

fun sendData() = true

fun awaitAcknowledge() = false

fun main() {
    runBlocking {
        println(sendDataAndAwaitAcknowledge()) // [false, true]
    }
}



回答2:


Use like this pattern:

    suspend fun sendDataAndAwaitAcknowledge() {
     val one = async { sendData() }
     val two = async { awaitAcknowledge() }
     println("The result is ${one.await() + two.await()}")
    }

as you can see, two suspending functions are called in third one and in parallel, the third suspending fun will wait to the two others finish their tasks.



来源:https://stackoverflow.com/questions/57457079/run-two-kotlin-coroutines-inside-coroutine-in-parallel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!