Android Kotlin Coroutines Setup and Basic Usage
October 5, 2018Why 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.
-
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:
- algo-trading
- algolia
- analytics
- android
- android-ktx
- android-permission
- android-studio
- apps-script
- bash
- binance
- bootstrap
- bootstrapvue
- chartjs
- chrome
- cloud-functions
- coding-interview
- contentresolver
- coroutines
- crashlytics
- crypto
- css
- dagger2
- datastore
- datetime
- docker
- eslint
- firebase
- firebase-auth
- firebase-hosting
- firestore
- firestore-security-rules
- flask
- fontawesome
- fresco
- git
- github
- glide
- godot
- google-app-engine
- google-cloud-storage
- google-colab
- google-drive
- google-maps
- google-places
- google-play
- google-sheets
- gradle
- html
- hugo
- inkscape
- java
- java-time
- javascript
- jetpack-compose
- jetson-nano
- kotlin
- kotlin-serialization
- layout
- lets-encrypt
- lifecycle
- linux
- logging
- lubuntu
- markdown
- mate
- material-design
- matplotlib
- md5
- mongodb
- moshi
- mplfinance
- mysql
- navigation
- nginx
- nodejs
- npm
- nuxtjs
- nvm
- pandas
- payment
- pip
- pwa
- pyenv
- python
- recylerview
- regex
- room
- rxjava
- scoped-storage
- selenium
- social-media
- ssh
- ssl
- static-site-generator
- static-website-hosting
- sublime-text
- ubuntu
- unit-test
- uwsgi
- viewmodel
- viewpager2
- virtualbox
- vue-chartjs
- vue-cli
- vue-router
- vuejs
- vuelidate
- vuepress
- web-development
- web-hosting
- webpack
- windows
- workmanager
- wsl
- yarn