July 2018
Intermediate to advanced
266 pages
7h 11m
English
An active job that is requested to be cancelled may enter a staging state called canceling. To request a job to cancel its execution, the cancel() function should be called:
fun main(args: Array<String>) = runBlocking { val job = launch { // Do some work here delay(5000) } delay(2000) job.cancel()}
Here, the execution of the job will be cancelled after 2 seconds; cancel() has an optional cause parameter. If an exception is the cause of the cancellation, it's a good practice to send it there; that way, it can be retrieved at a later time:
fun main(args: Array<String>) = runBlocking { val job = launch { // Do some work here delay(5000) } delay(2000) // cancel with a cause job.cancel(cause = Exception("Timeout!"))}
There is also a ...
Read now
Unlock full access