Leave a rating/review
Hi! This is the ninth episode of the course! You should have learned a lot so far! :]
In this episode you’ll explore the async coroutine builder, and the await function. You’ll learn how to use them to execute multiple coroutines in parallel.
The async builder is very similar to the launch. It has the same parameters and starts a coroutine in the same way.
But, the difference is in the return type. The async builder returns a Deferred object.
It’s a special type of a job, which can return a result.
To retrieve the result you need to use the await() function.
It suspends the coroutine until the result is ready. Next it either returns the result, or throws an exception if the coroutine has failed or cancelled.
Let’s see a live example! Open the AwaitScreen file in Android Studio.
There is a button there, which starts two async coroutines. Each of them waits a few seconds and then returns a result.
For now, the results aren’t going anywhere. Even Android Studio warns that “Deferred result is unused”.
Start with storing the deferred results in a list.
val deferredResults = listOf(
coroutineScope.async { doSomething(4) },
coroutineScope.async { doSomething(2) },
)
Next, you can use the awaitAll() function to wait for all the results. Finally, you can print them to the LogCat.
val results = deferredResults.awaitAll()
Log.d("AwaitScreen", "Results: $results")
Run the app and go to the Await Screen!
Click on the button and open the LogCat
Look at the logs. Despite the fact that the second coroutine was started later, it finished earlier. It means that both coroutines ran in parallel.
Note the awaitAll() function. It is not the same as calling await() on each deferred result in a loop!
The awaitAll() function will throw an exception immediately, if any of the coroutines fails. Individual await() will throw only when its own coroutine fails.
Even if all the next coroutines have failed it will still wait for the result.
That was a quick lesson. I hope you understand the differences between the launch and the async builders now.
There is also one more difference in terms of error handling. But, it is a topic for the next episode.