ensureActive
Throws the CancellationException that was the scope's cancellation cause if the scope is no longer active.
Coroutine cancellation is cooperative and normally, it's checked if a coroutine is cancelled when it suspends, for example, when trying to read from a channel that is empty.
Sometimes, a coroutine does not need to perform suspending operations, but still wants to be cooperative and respect cancellation.
ensureActive function is inteded to be used for these scenarios and immediately bubble up the cancellation exception:
val watchdogDispatcher = Dispatchers.IO.limitParallelism(1)
fun backgroundWork() {
println("Doing bookkeeping in the background in a non-suspending manner")
Thread.sleep(100L) // Sleep 100ms
}
fun postBackgroundCleanup() = println("Doing something else")
// Part of some non-trivial CoroutineScope-confined lifecycle
launch(watchdogDispatcher) {
while (true) {
// Repeatatively do some background work that is non-suspending
backgroundWork()
ensureActive() // Bail out if the scope was cancelled
postBackgroundCleanup() // Won't be invoked if the scope was cancelled
}
}
This function does not do anything if there is no Job in the scope's coroutineContext.
See also
Ensures that current job is active. If the job is no longer active, throws CancellationException. If the job was cancelled, thrown exception contains the original cancellation cause.
This method is a drop-in replacement for the following code, but with more precise exception:
if (!job.isActive) {
throw CancellationException()
}
Ensures that job in the current context is active.
If the job is no longer active, throws CancellationException. If the job was cancelled, thrown exception contains the original cancellation cause. This function does not do anything if there is no Job in the context, since such a coroutine cannot be cancelled.
This method is a drop-in replacement for the following code, but with more precise exception:
if (!isActive) {
throw CancellationException()
}