July 2018
Intermediate to advanced
266 pages
7h 11m
English
When we are already in a suspending function we can change the context for a block of code using withContext(). This is a suspending function that will use the given context to execute the block of code. For example, if we need to execute an operation in a different thread but we will always wait for it to finish before continuing. Let's start with this example:
fun main(args: Array<String>)= runBlocking { val dispatcher = newSingleThreadContext("myThread") val name = async(dispatcher) { // Do important operation here "Susan Calvin" }.await() println("User: $name")}
Here we are using async() to do an operation using the context dispatcher, but since async() returns a Deferred<String>, we are forced ...
Read now
Unlock full access