July 2018
Intermediate to advanced
266 pages
7h 11m
English
As covered in the previous chapter, when the execution of a coroutine is cancelled, an exception of the type CancellationException will be thrown inside the coroutine, causing the coroutine to end. Since an exception is thrown inside the coroutine, we can use a try-finally block to do some cleaning operations like closing resources – or for logging as well. This will look something like the following:
fun main(args: Array<String>) = runBlocking { val duration = measureTimeMillis { val job = launch { try { while (isActive) { delay(500) println("still running") } } finally { println("cancelled, will end now") } } delay(1200) job.cancelAndJoin() } println("Took $duration ms")}
This code will print "still running" every 500 milliseconds ...
Read now
Unlock full access