A Peek at Continuations
We'll cover the following...
Preserving the state
Methods marked with the suspend annotation may return data. However, coroutines may suspend execution and may switch threads. How in the world does the state get preserved and propagated between threads?
To explore this further, let’s take a look at an example that brings out this concern clearly. Instead of creating .kts files, we’ll create .kt files so it’s easy to compile to Java bytecode and examine.
import kotlinx.coroutines.*class Compute {fun compute1(n: Long): Long = n * 2suspend fun compute2(n: Long): Long {val factor = 2println("$n received : Thread: ${Thread.currentThread()}")delay(n * 1000)val result = n * factorprintln("$n, returning $result: Thread: ${Thread.currentThread()}")return result}}
The Compute class has two methods, one marked with suspend
. The compute1()
method is simple; it returns the double of the given input. The compute2()
method does the same thing, except it yields the flow of execution to other pending tasks and may potentially switch threads midway.
Let’s create a main()
function to execute the compute2()
function, a couple of times, within coroutines.
import kotlinx.coroutines.*fun main() = runBlocking<Unit> {val compute = Compute()launch(Dispatchers.Default) {compute.compute2(2)}launch(Dispatchers.Default) {compute.compute2(1)}}
We assign a single expression function to the ...