Open In App

Kotlin Coroutines on Android

Asynchronous programming is very important and it’s now a common part of modern application. It increases the amount of work that your app can perform in parallel. This allows running heavy tasks away from UI Thread in the background, which ultimately gives a smooth and better experience to the user of the app.

Coroutine in Kotlin

The Kotlin team defines coroutines as “lightweight threads”. They are sort of tasks that the actual threads can execute. Coroutines were added to Kotlin in version 1.3 and are based on established concepts from other languages. Kotlin coroutines introduce a new style of concurrency that can be used on Android to simplify async code.



The official documentation says that coroutines are lightweight threads. By lightweight, it means that creating coroutines doesn’t allocate new threads. Instead, they use predefined thread pools and smart scheduling for the purpose of which task to execute next and which tasks later.

Coroutines are basically of two types:



Kotlin implements stackless coroutines, it means that the coroutines don’t have their own stack, so they don’t map on the native thread.

Why we need coroutines?

As we know android developers today have many async tools in hand. These include RxJava, AsyncTasks, Jobs, Threads. So why there is a need to learn something new?

Kotlin Coroutines Features

Coroutines is the recommended solution for asynchronous programming on Android. Some highlighted features of coroutines are given below.

Kotlin Coroutines vs Threads

Kotlin Coroutines Dependencies

Add these dependencies in build.gradle app-level file.




// dependencies to import in project 
dependencies 
{
  implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:x.x.x"
  implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:x.x.x"
}

Note: x.x.x is the version of the coroutine.

Kotlin Coroutines Example

Let’s say we want to fetch some users from the database and show it on the screen. For fetching the data from the database we have to perform the network call, fetch the user from the database, and show it on the screen. Fetching the user can be done by using either by using callbacks or coroutines.

Using Callbacks:




// pseudo kotlin code for demonstration
// involves a series of callbacks from fetchAndShowUser 
// to fetchUser and then to showUser
fun fetchAndShowUser() 
{
  fetchUser 
  {
    user -> showUser(user)
  }
}

Using Coroutines:




//pseudo kotlin code for demonstration
suspend fun fetchAndShowUser() 
{
  // fetch on IO thread
  val user = fetchUser() 
  // back on UI thread
  showUser(user)
}

As discussed above using callbacks will decrease the code readability, so using coroutines is much better to use in terms of readability and performance as well. As discussed above Coroutines has many advantages apart from not having callbacks, like they are nonblocking, easy, and nonexpensive to create.       


Article Tags :