February 2018
Intermediate to advanced
350 pages
7h 35m
English
Our first option is to use a different context for our update operation:
import kotlinx.coroutines.experimental.*fun main(args: Array<String>) = runBlocking { var counter = 0 val counterContext = newSingleThreadContext("CounterContext") val time = measureTimeMillis { repeatInParallel(1_000_000) { withContext(counterContext) { counter++ } } } println("counter = $counter") println("time = $time")}
The withContext function executes a block in a specific coroutine context—in this case, a single-threaded one. Switching context is a powerful technique that lets us manipulate, in a fine-grained way, how our code runs.
Read now
Unlock full access