Coroutines were introduced with Kotlin v1.1 in 2017 and since then we have experienced asynchronous simplicity at its finest. Coroutines bring in a volley of power-packed features to the game and most of us have already witnessed it by now.
While developing an Android app, you will come across multiple scenarios where coroutines could be implemented. The most common one is while making multiple network calls asynchronously.
In this article, we would not be talking about the basics or fundamentals of Coroutines but rather discuss some scenarios that we generally encounter while dealing with asynchronous network calls and how we can easily implement it with the help of Coroutines.
Some basic knowledge and fundamentals of Kotlin and Coroutines.
This article talks about dealing with some common scenarios that are encountered while implementing multiple network calls asynchronously. Some are pretty straightforward, while some require special handling.
These scenarios are:
Let's take a deep dive into these scenarios, shall we?
These calls are subtly made in the background while ignoring the response. Consider a scenario where 10 network calls are to be made without blocking the application UI. This could be achieved with the ‘launch’ extension of ‘CoroutineScope’. It returns a ‘Job’ object that can give us information about that specific Job. Something like this:
To keep it simple, we are making the same network call ten times in a loop. join() is called once all the coroutine Jobs have completed.
Notice that the network call ID does not appear in incremental order. This is because, essentially, coroutines are light-weight threads. Here, every ‘launch’ function is running concurrently with respect to each other.