ensureActive

fun CoroutineScope.ensureActive()

Ensures that current scope 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 scope's coroutineContext.

This method is a drop-in replacement for the following code, but with more precise exception:

if (!isActive) {
throw CancellationException()
}

See also


fun Job.ensureActive()

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

fun CoroutineContext.ensureActive()

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