September 2019
Intermediate to advanced
462 pages
11h 3m
English
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 * 2 |
| | suspend fun compute2(n: Long): Long { |
| | val factor = 2 |
| | println("$n received : Thread: ${Thread.currentThread()}") |
| | delay(n * 1000) |
| | val result = n * factor |
| | println("$n, returning $result: ... |
Read now
Unlock full access