Making Asynchronous Network Calls With Kotlin Coroutines in Android

Photo by Fabio Bracht on Unsplash

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:

  1. Fire-and-forget network calls.
  2. Canceling other network calls if at least one call fails.
  3. Continue execution of other network calls even if a single API call fails.
  4. 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:

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.

LogCat Output

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.

我来评几句
登录后评论

已发表评论数()

相关站点

+订阅
热门文章