Coroutines in Kotlin
Dmytro Zaitsev
Team Leader @ Lóhika
Blocking VS Non-blocking
v1: Sequential
fun postItem(item: Item) {

val token = prepareToken() // 1

val post = submitPost(token, item) // 2

processPost(post) // 3

}
v2: Async callbacks
fun postItem(item: Item) {

prepareTokenAsync { token -> // 1

submitPostAsync(token, item) { post -> // 2

processPost(post) // 3

}

}

}
Callback hell
v3: Reactive
fun postItem(item: Item) {

observeToken()

.concatMap { token -> observePost(token, item) }

.subscribe { post -> processPost(post) }

}
v4: Coroutines
fun postItem(item: Item) {

launch(CommonPool) {

val token = prepareToken() // 1

val post = submitPost(token, item) // 2

processPost(post) // 3

}

}
Experimental status
Kotlin 1.1
-Xcoroutines=enable
kotlin.coroutines.experimental -> kotlin.coroutines
Terminology
coroutine
suspending functionsuspending lambda
suspending function type
coroutine builder
suspension point
continuation
A coroutine is…
an instance of suspendable computation
similar to a daemon thread, but very light-weight
similar to a future or promise
Why coroutines?
threads are expensive to keep and switch
your code is single threaded
you’ve got lots of mutable states
suspend fun
computation that can be suspended
Standard API
• Language support (`suspend` keyword)
• low-level basic API (stdlib: kotlin.coroutines)
• high-level APIs that can be used in user code
Low-level API
(kotlin.coroutines)
• kotlin.coroutines.experimental
• create/start/suspendCoroutine()
• Continuation interface
• @RestrictSuspension annotation
• kotlin.coroutines.experimental.intrinsics
• suspendCoroutineOrReturn()
Continuation
interface Continuation<in T> {

val context: CoroutineContext

fun resume(value: T)

fun resumeWithException(exception: Throwable)

}
Patterns
• generators/yield: C#, Python, Scala
• async/await: C#, ECMAScript, Dart
• channels, select: Go
• actors: Scala
Generators API in
kotlin.coroutines
kotlin.coroutines.experimental:
• buildSequence()
• buildIterator()
buildSequence {

print("Start")

yield(1) // suspension point



var prev = 0

var cur = 1

while (true) {

print(“Next")
val next = prev + cur

yield(next) // suspension point



prev = cur

cur = next

}

print("End") // unreachable code

}.take(8).forEach { print(" $it ") }

// Output: Start 1 Next 1 Next 2 Next 3 Next 5 Next 8 Next 13 Next 21
kotlinx.coroutines
• kotlinx-coroutines-core
• integration
• guava, jdk8, nio, quasar
• reactive
• reactive, reactor, rx1, rx2
• ui
• android, javafx, swing
runBlocking
for main functions
and tests
delay
like Thread.sleep(),
but non-blocking
launch
fire and forget
(Job)
async
promise returned
(Deferred + await)
Channel
transfers values
between coroutines
produce
produces a stream of values
by sending them to a channel
(ProducerJob)
actor
deals with it’s mailbox
(ActorJob)
select
waits for the result of
multiple suspending
functions
Job lifecycle
New Active
Cancelling
Completed
Cancelled
Job states
State isActive isCompleted isCancelled
New
- - -
Active
+ - -
Completed
- + -
Cancelling
- - +
Cancelled
- + +
val deferred = async(CommonPool) {

throw SomeException("I'm thrown inside a coroutine")

}

try {

deferred.await() // re-throws

} catch (e: SomeException) {

log(e.message)

}
Exception handling
WeakReference “life hack”
suspend operator fun <T> WeakReference<T>.invoke(): T
= suspendCoroutineOrReturn {
get() ?: throw CancellationException()
}
val activityRef = WeakReference(this)

launch(CommonPool) {

activityRef().expensiveComputation()

}
Demo
A lot more left…
Coroutine dispatchers
Mutable state and concurrency
UI programming
Reactive streams
Links
Andrey Breslav FAQ:

https://discuss.kotlinlang.org/t/experimental-status-of-coroutines-in-1-1-and-
related-compatibility-concerns/2236
Design document (KEEP):

https://github.com/Kotlin/kotlin-coroutines/blob/master/kotlin-coroutines-
informal.md
Full kotlinx.coroutines API:

http://kotlin.github.io/kotlinx.coroutines
Coroutines guide by Roman ELizarov:

https://github.com/Kotlin/kotlinx.coroutines/blob/master/coroutines-guide.md
Thank you!
@DmitriyZaitsev

Coroutines in Kotlin