Run two Kotlin coroutines inside coroutine in parallel
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]
}
}
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.