Learn asynchronous programming with Kotlin Coroutines

Arsy Opraza
UNIKOM Codelabs
Published in
3 min readJan 11, 2022

In this post, I will share what I have learned about Kotlin Coroutines a few weeks ago.

Before we talk about coroutines, we must talk about asynchronous vs synchronous.

What are asynchronous and synchronous?

  • An asynchronous, code can be running without waiting for the previous one to finish, we can run multiple tasks at the same time. For example in real life, asynchronous is like you ordered some coffee in a coffee shop while waiting for your coffee, you can do another thing like a meeting with your colleague or just scroll your social media.
  • A synchronous, code can be running after the previous one is finished. With synchronous, we only can run a single task at the same time. For example in real life, synchronous is like you queue in line at the cashier, you can be served after in front of you served by the cashier.
source

In the example above, synchronous Customers can be run after Products are finished and Orders can be run after Customers are finished, but with asynchronous, we can run products and customers at the same time, so we can save a lot of time with asynchronous!

So, what is Kotlin Coroutine?
A coroutine is a concurrency design pattern that you can use on Android to simplify code that executes asynchronous tasks that keeps your app responsive while running long-running tasks such as network call or processing data from a database.

Coroutine help to manage long-running tasks and UI (user interface) becomes responsive while running long-running tasks and provides feedback for users, so user can notice your app doing the long-running task which takes a lot of time.

Coroutine can solve problems from these:

  • Long-running tasks (network request, reading data from database)
  • Main-safety, save to call suspend function from main thread.

Manage long-running tasks

Coroutines build upon regular functions by adding two new operations. In addition to invoke (or call) and return, coroutines add suspend and resume.

  • suspend — pause the execution of the current coroutine, saving all local variables
  • resume — continue a suspended coroutine from the place it was paused

You can call suspend functions only from other suspend functions or by using a coroutine builder such as launch to start a new coroutine.

The following example shows a simple coroutine implementation for a hypothetical long-running task:

suspend fun fetchDocs() {                             
val result = get("https://developer.android.com")
show(result)
}

suspend fun get(url: String) = withContext(Dispatchers.IO) {
/* ... */
}

Coroutines for main-safety

In Kotlin, all coroutines must run in a dispatcher, even when they’re running on the main thread. Coroutines can suspend themselves, and the dispatcher is responsible for resuming them.

To specify where the coroutines should run, Kotlin provides three dispatchers that you can use:

  • Dispatchers.Main — Use this dispatcher to run a coroutine on the main Android thread. This should be used only for interacting with the UI and performing quick work. Examples include calling suspend functions, running Android UI framework operations, and updating LiveData objects.
  • Dispatchers.IO — This dispatcher is optimized to perform disk or network I/O outside of the main thread. Examples include using the Room component, reading from or writing to files, and running any network operations.
  • Dispatchers.Default — This dispatcher is optimized to perform CPU-intensive work outside of the main thread. Example use cases include sorting a list and parsing JSON.

Starting a coroutine

You can start coroutines in one of two ways:

  • launch starts a new coroutine and doesn't return the result to the caller. Any work that is considered "fire and forget" can be started using launch.
  • async starts a new coroutine and allows you to return a result with a suspend function called await.

Here is an example using coroutine with MVVM architecture:

To authenticate users we use network requests, so use Dispatchers.IO instead of Dispatchers.Main

For best practices coroutines in Android, you can read in Best practices for coroutines in Android | Android Developers.

--

--