Member-only story
Making Asynchronous Network Calls With Kotlin Coroutines in Android

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.
Pre-requisite
Some basic knowledge and fundamentals of Kotlin and Coroutines.
Objective
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:
- Fire-and-forget network calls.
- Canceling other network calls if at least one call fails.
- Continue execution of other network calls even if a single API call fails.
- Canceling other network calls only if a certain error condition is encountered.
Let's take a deep dive into these scenarios, shall we?
Fire-and-forget(FAF) network calls
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: