Kotlin Coroutines in Android

Tram Ho

What is coroutines

Basically, coroutines are lightweight threads. It allows us to write asynchronous code.

How to import Corlinines in Android?

According to the repository of Kotlin Coroutines Github, we need to import kotlinx-coroutines-core and kotlinx-coroutines-android (This library supports the main Android stream like library io.reactivex.rxjava2: rxandroid unsaved exceptions Can be recorded before doing Android app crassh.). Furthermore, if you use RxJava in your project, please add kotlinx-coroutines-rx2 to use coroutines with RxJava. This library helps convert RxJava to Coroutines. Import them into your project by adding the following code to app / build.gradle.

and add the latest version of Kotlin to your root / build.gradle.

Basic coroutines

First, Coroutines basically looks like this:

We take the data from the server in the background thread and then update the user interface in the main thread.

Suspending functions

There is a special function called Suspending function in Corlinines of Kotlin, we can declare the function by keyword. The suspension function can suspend the execution of a coroutine, which means it will wait until the suspension function is active again. Since this post is for the Coroutines basics, we will discuss hanging functions in more detail in another post. Let’s return to the code above, it can be divided into four parts:


Define a scope for new coroutines. Each coroutine builder is an extension on CoroutineScope and inherits its coroutineContext to automatically pass both context and abort elements.

All coroutine runs inside a CoroutineScope and it needs a CoroutineContext (I’ll talk about it later) as a parameter. There are several scopes we can use:

  1. CoroutineScope

Create scope with custom CoroutineContext. For example, to determine the flow, parent job, and exception handling according to our needs.

  1. MainScope

Create the main scope for UI components. It is running on the main thread with Monitor (), which means that the failure of one of its subtasks has already been affecting others.

  1. Global

This is a scope that is not tied to any job. It is used to launch the top-level coroutines that are active over the entire application period and are not canceled early.


Coroutine always executes in a number of contexts denoted by a value of type CoroutineContext. CoroutineContext is a set of elements, to define thread policy, exception handling, coroutine lifetime, etc. We can use the addition operator to combine CoroutineContext elements. There are three most important Coroutine contexts – Dispatch, CoroutineExceptionHandler and Job.

  1. Dispatchers

    Determine which threads run coroutine. A coroutine can switch dispatchers anytime with withContext ().

  • Dispatchers.Default: Use a shared background pool of the thread. By default, the maximum number of threads used by this Dispatchers is equal to the number of CPU cores, but at least two.
  • Dispatchers.IO : Share topics with Dispatchers.Default, but the number of topics is limited by kotlinx.coroutines.io .
  • Dispatchers.Main: Equivalent to the main thread of Android.
  • Dispatchers.Unconfined: A coroutine dispatcher does not limit any specific thread. Coroutine executes in the current thread first and allows coroutine to continue in any thread used by the corresponding suspending function.

  1. CoroutineExceptionHandler Exception handling.

Usually, unexplored exceptions can only result from coroutines created by the launch builder. An asynchronous coroutine always catches all its exceptions and presents them in the Delay result object.

Example 1: Cannot catch IOException () with outside try-catch. We cannot wrap the entire CoroutineScope with a try-catch, the application will still crash.

Example 2: Getting IOException () with CoroutineExceptionHandler. If the exception is not CancellingException (), for example, IOException (), then it will be passed to CoroutineExceptionHandler.

Example 3: CancellingException () is ignored. If the exception is CancellingException then it will be ignored (Because it’s the mechanism supposedly to cancel the coroutine running, and this exception won has been passed to CoroutineExceptionHandler.)

Example 4: Use invokeOnCompletion to get all exception information. CancellingException () will not be passed to CoroutineExceptionHandler. If we want to print some information after the exception occurs, we can use invokeOnCompletion to achieve it.

Share the news now

Source : Viblo