Introduction to Kotlin Coroutines

Balarka Velidi
4 min readMar 18, 2020
Photo by amirali mirhashemian on Unsplash

Brief History:

Google made a huge announcement in its I/O ’19 conference that Kotlin will be supported as first class language for Android development. Along with that, it introduced Coroutines in Kotlin to make asynchronous, non-blocking programming intuitive and performant. Since then coroutines has become very popular, very fast in Android developer community. Coroutines by themselves aren’t new to computer programming. They were referred to as programming components to represent subroutines for multitasking during assembly programming days.

Why another Library for multi-threading?

In our existing Java/JVM world, we have classic Threads, Executors and other mechanisms to achieve multi-threading. So what is the need for yet another way to create/maintain multiple threads? What are we achieving here that we aren’t able so far?

In any typical asynchronous programming, the challenge is to coordinate all the parallel executing threads, ensure they are not deadlocked and gather their results after they are done. If you look at any web based programming languages (say Javascript), this is a very common paradigm in which, we invoke a function, not knowing when we get the result from that function, we give that function another function as “callback function” so that it can call this callback function once it is has the result ready. Given a set of asynchronous tasks, that need to happen one after another, this pattern leads into a staircase of callbacks, popularly known as “callback hell”. This problem is not different to any non-web programming languages either, which is one key aspect (among others) that Kotlin Coroutines aims to solve for.

Coroutines are light weight threads in kotlin. A standard function is a block of code instructions line by line executed and operated on the result of a previously executed instructions. A standard function is a blocking function, meaning the caller has to wait till the function is complete and returns a result for the caller to consume and continue. This is essentially where coroutines differ though. With Coroutines, a function is named as “suspend” that has one or more of body statements running longer to complete, which means, it is not preferred to keep the caller function waiting for this suspend function’s body to complete.

Let’s take a basic example, where we call the API server to fetch a list of products, and store them in the database. We are looking at 2 operations that are asynchronous in nature and can take many seconds to complete (network fetch, db write).

Using a standard function, we call the network API first, and once the response is obtained, parse them and write them to the database. However, we need to link the second asynchronous operation with the first by sending it as callback.

Example:

fun fetchProducts() {
api.fetchProducts { jsonResponse ->
val products = parseProducts(jsonResponse)
storeProductsInDB(products)
}
}

Note, we haven’t considered any error handling logic in the above function, but when added it gets complicated to understand and maintain.

With Coroutines in action, there is no need for callback, and the 2 asynchronous operations can be written as if they are sequential statements and still achieve the same result as above.

Below is the coroutine version:

suspend fun fetchProducts() {
val jsonResponse = api.fetchProducts() // 1st asynchronous function
val products = parseResponse(jsonResponse)
storeProductsInDB(products) // 2nd asynchronous function
}

Coroutines in Android:

Coroutines really shine bright in Android development as well, where the main objective is Main thread safety. In mobile platforms, the UI thread/Main thread is responsible for drawing views on the screen, and responding to the user interactions and is super busy all the time constantly running in a loop and dispatching actions based on user events. Making the main thread to work on any longer tasks is anti-pattern that leads to a lag/jitter in the UI responsiveness and must be avoided at all costs. So, how does a User interface screen load the data from server and show it to the screen you may ask? This is done by creating a new thread (say I/O thread) from Main thread, make the API call on that I/O thread and once the API response is fetched, switch to the main thread and render the data on the screen!

This is where Kotlin coroutines come in handy! Coroutines come with a context/scope in which a certain action can be performed and here the scope will be based on where the suspend function is triggered. For example: when triggered inside activity the scope is Main thread, and once a new scope is created inside the coroutine, it changes to that locally created scope and continue the work.

Thanks for reading! Hope you will experience the joy of writing coroutines as I did!

--

--

Balarka Velidi

Lead (Staff) Android Engineer @intuit. I write mostly about Android development, framework APIs, advancements etc. follow me @balarka on twitter.