Kotlin Coroutines in Android — Basics

Learn the basic concepts and usage of Kotlin Coroutines.

Evan Fang
The Startup

--

What is Coroutines

Essentially, coroutines are light-weight threads. It lets us write asynchronous, non-blocking code in a sequential way.

How to import Kotlin Coroutines in Android?

According to the Kotlin Coroutines Github repo, we need to import kotlinx-coroutines-core and kotlinx-coroutines-android (This library supports for the Android main thread just like the library io.reactivex.rxjava2:rxandroid for RxJava, and also makes sure the uncaught exceptions could be logged before crashing Android application.). Furthermore, if you’re using RxJava in your project, please add kotlinx-coroutines-rx2 for using coroutines with RxJava as well. This library helps to transfer the RxJava to Coroutines.

Import them to your project by adding the following code to app/build.gradle.

implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.2'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.2'
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-rx2:1.3.2"

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

buildscript {
ext.kotlin_version = '1.3.50'
repositories {
jcenter()
...
}
...
}

--

--

Evan Fang
The Startup

An Android/Flutter engineer at LINE Corporation.