Android Kotlin Coroutines Setup and Basic Usage

October 5, 2018

Why use Kotlin Coroutines?

Setup Android Kotlin Coroutines

Setup an Android Project with Kotlin.

Edit Module build.gradle.

dependencies {
    ...
    // https://mvnrepository.com/artifact/org.jetbrains.kotlinx/kotlinx-coroutines-android
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:0.23.4'
}

Edit gradle.properties.

kotlin.coroutines=enable

Basic Usage

Launch a background coroutine.

launch {
    // do something
}

Launch a couroutine in UI Thread.

launch(UI) {
    // update UI
}

You can launch a background coroutine for some heavy task, then launch UI coroutine to update the UI.

launch {
    // do some heavy processing

    launch(UI) {
        // update UI
    }
}

If you need to wait for a result from a coroutine, use async.

launch(UI) {
    var deferred = async(CommonPool) {
        getRemoteName()
    }

    val name = deferred.await()
    nameEditText.text = name
}

You can write a cancellable coroutine.

You can write suspend function which must be called within coroutines.

Use coroutines to delay a job.

Convert Callback Into Kotlin Coroutines Suspend or Deferred.

Kotlin Android Coroutine Context: Default Dispatcher, CommonPool and UI

You can use Retrofit2 with Kotlin Coroutines to remove all the messy callbacks.

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.