KEMBAR78
Asynchronous Programming with Kotlin | PDF
Asynchronous programming
Hadi Hariri
Approaches
Threading
Threading
• Complex - state mutations, UI threads, debugging
• Unviable - single threaded environments
• Limited - underlying operating system
• Expensive - context switches
Callbacks
Callbacks
• Complex - Error handling
• Unreadable - Callback Hell
{
{
{
{
{
{
}
}
}
}
}
}
Promises and Futures
Promises and Futures
• Complex - error handling can be complicated
• Paradigm - new ways of combining, learning new
combinators, etc.
Reactive Extensions
interface Observable<out T> {

fun Subscribe(observer: Observer<T>)

}
interface Observer<in T> {

fun onNext(t: T)
fun onError(e: Exception)
fun onCompleted()

}

Reactive Extensions
• Paradigm - new ways of combining, learning new
combinators, etc.
Everything is a stream. And it’s observable.
Kotlin Coroutines
Do async, the same way you’d do sync
In essence…
• Same way of thinking for sync and async
• Same way of doing things (exception handling, loops, etc.)
• Same constructs
Coroutines
• Suspendable Computation
• A function can be suspended, and later resumed
• Co-operative multitasking a.k.a. non-preemptive
• State machine with CPS
• Lightweight threads
How they look
explicit coroutine context
1
2
3
suspending function
natural signature
How they work
callback
Kotlin
Java/JVM
How they’re implemented
Kotlin
Java/JVM
Let’s see some code!
Thank you!

Asynchronous Programming with Kotlin