
Photo by
Lyndon Li on
Unsplash
Kotlin Coroutines
Posted: 12 Jul 2017.
Last modified on 08-Feb-25.
This article will take about 2 minutes to read.
Coroutines are experimental in kotlin 1.1+
This means that they are currently stable, but the syntax for them might change.
They are enabled via the library kotlinx.coroutines, so they are not coupled together with the language
But what are they?
Threads
- The operating system determines when to switch threads according to its scheduler (an OS kernal algorithm)
- Since the operating system has no insight in to the current state of the program, it has to interrupt, which causes an expensive context switch.
- This involves saving unrelated context in memory, so the thread can guarantee it will resume correctly.
Coroutines:
- the programming and programming language determine when teo switch coroutines
- the tasks are cooperatively multitasked by pausing and resuming functions at set points, typically (but not necessarily) within a single thread.
Why should we use coroutines?
- User can define context in which code block runs (UI Thread)
- Kotlin features make defining a coroutine easy - they are launched by a coroutine builder
- sunchronous code does not necessarily have to change to be made async
- Performance gains via developer defined context switching are huge
- Tiny memory footprint - kilobytes instead of megabytes
- Easy to use keywords:
yield and suspend
- Callback hell can be flattened into intuitive code
- Coroutines introduce the concept of yield and suspend
- yield will suspend the current execution of the coroutine, allowing - another coroutine to take over.
- only suspend functions are allowed to yield and eb launched via coroutine builders
- It allows us to program asynchronously with code that looks synchronous
// kotlin 1.1
val fibinacciSeq = buildSequence {
var a = 0
var b = 0
yield(1)
while(true) {
yield(a + b)
a = b.also { b = a + b }
}
}
Currently there are only 2 coroutine builders in kotlin-stdlib
- buildSequence
- buildIterator
Other coroutine builders include
launch()
launch(UI)
runBlocking()
we can always define custom coroutine builders via functional kotlin language constructs.
References: