问题
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