Why use Kotlin Coroutines?
- My favourite reason: Kotlin Coroutines allow writing asynchronous code in a sequential manner (no more callbacks, and sequential codes are very readable). I used to use RxJava.
- Coroutine is more lightweight than a thread.
- Really nice syntax.
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: