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.
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.
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
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With