Canceling

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 cancelAndJoin() function. As its name suggests, this will not only cancel the execution but also suspend the current coroutine until the cancellation has been completed.

Currently, there is no implementation of cancelAndJoin() that allows a cause to be passed.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.176.88