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 await a Deferred that has not yet completed.

Sometimes, a coroutine does not need to perform suspending operations but still wants to be cooperative and respect cancellation.

ensureActive function is intended to be used for these scenarios and immediately bubble up the cancellation exception:

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(Dispatchers.IO) {
while (true) {
// Repeatedly 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.

For ensuring that the current coroutine context and not some scope's context is active, the following form can be used instead:

suspend fun doSomething() {
// throw if we are not allowed to suspend
currentCoroutineContext().ensureActive()
// ...
}

Alternatively, yield can be used to both ensure that currentCoroutineContext is active and give other coroutines a chance to run on this thread:

suspend fun doSomething() {
// yield the thread to other coroutines
yield()
// ...
}

See also

for a version that gives other coroutines a chance to run on this thread.

for a version that returns a boolean value instead of throwing an exception.


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()
}