Coroutine ͓͞Β͍1
• No longer experimental since Kotlin v1.3
• launch
• async
• await
• suspend
1 https://kotlinlang.org/docs/tutorials/coroutines/coroutines-basic-jvm.html
Slide 2
Slide 2 text
launch
• Coroutine
launch {
delay(1000)
}
Slide 3
Slide 3 text
launch {
delay(1000)
}
• launch runs coroutine on shared thread pool
• delay suspends coroutine (suspend function)
• when coroutine is waiting, the thread is returned to thread
pool and resumes later with free thread in the pool
• runBlocking runs new coroutine and blocks current thread
Slide 4
Slide 4 text
async, await
val deferred = (1..1_000_000).map { n ->
async {
n
}
}
val sum = deferred.sumBy { it.await() }
• async is like launch but returns Deferred.
• Deferred has await()
• await() returns T, result of the coroutine
Slide 5
Slide 5 text
async, await
• await() must be in coroutine. It suspends the computation
finishes.
• Coroutines can suspend only in coroutine or suspend
function
Error: Suspend functions are only allowed to be called from a
coroutine or another suspend function
Slide 6
Slide 6 text
suspend
fun workload(n: Int):Int {
delay(100) // <- suspend function
returns n
}
Error: Suspend functions are only allowed to be called from a
coroutine or another suspend function
• Add suspend modifier to function to fix this and call from a
coroutine or another suspend function
suspend fun workload(n: Int): Int { ... }