A first walk into Kotlin coroutines on Android

Understanding how coroutines work

fun <T> async(block: suspend () -> T)
suspend fun mySuspendingFun(x: Int) : Result {

}
async {
val res = mySuspendingFun(20)
print(res)
}

Using Anko for coroutines

async(UI) {

}
async(UI) {
val r1: Deferred<Result> = bg { fetchResult1() }
val r2: Deferred<Result> = bg { fetchResult2() }
updateUI(r1.await(), r2.await())
}
async(UI) {
val r1 = bg { fetchResult1() }
val r2 = bg { fetchResult2() }
updateUI(r1.await(), r2.await())
}
textView.onClick {
val r1 = bg { fetchResult1() }
val r2 = bg { fetchResult2() }
updateUI(r1.await(), r2.await())
}
compile “org.jetbrains.anko:anko-sdk15-coroutines:$anko_version”
compile “org.jetbrains.anko:anko-appcompat-v7-coroutines:$anko_version”
compile “org.jetbrains.anko:anko-design-coroutines:$anko_version”

Using coroutines in an example

compile “org.jetbrains.anko:anko-coroutines:$anko_version”
kotlin.coroutines=enable
async(UI) {
val id = intent.getLongExtra(ID, -1)
val result = bg { RequestDayForecastCommand(id)
.execute() }
bindForecast(result.await())
}
val ref = asReference()
val id = intent.getLongExtra(ID, -1)
async(UI) {
val result = bg { RequestDayForecastCommand(id).execute() }
ref().bindForecast(result.await())
}
private fun loadForecast() {val ref = asReference()
val localZipCode = zipCode
async(UI) {
val result = bg { RequestForecastCommand(localZipCode).execute() }
val weekForecast = result.await()
ref().updateUI(weekForecast)
}
}
private fun loadForecast() = async(UI) {
val result = bg { RequestForecastCommand(zipCode).execute() }
updateUI(result.await())
}

Freelance trainer. I help you and your company to become Kotlin experts. Visit https://antonioleiva.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store