Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run two Kotlin coroutines inside coroutine in parallel

Tags:

People also ask

Can coroutines run parallel?

The key point here is to use async to do the network calls in parallel. Learn more about async from here. Similarly, we can do any type of background tasks in parallel using Kotlin Coroutines. Let's take another example.

Are Kotlin coroutines parallel?

Kotlin's Coroutines enabling you to write parallel code easily, in a sequential way, and without worrying about the contextual overheads you know from using threads in Java.

Are coroutines multithreading?

Multithreaded coroutinescoroutines library provides support for using multiple threads. It is a separate branch for the reasons listed in the future concurrency model blog post. However, you can still use the multithreaded version of kotlinx.


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?