Android Kotlin Coroutines Setup and Basic Usage

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:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.