isActive

Returns true when the Job of this CoroutineScope is still active (has not completed and was not cancelled yet).

Coroutine cancellation is cooperative, and usually, 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.

The isActive property is intended to be used for scenarios like this:

fun backgroundWork() {
println("Doing bookkeeping in the background in a blocking manner")
Thread.sleep(100L) // Sleep 100ms
}
// Part of some non-trivial CoroutineScope-confined lifecycle
launch(Dispatchers.IO) {
while (isActive) {
// Repetitively do some background work that is non-suspending
backgroundWork()
}
}

This function returns true if the scope does not contain a Job in its context. This can only happen for GlobalScope and malformed coroutine scopes.

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

suspend fun tryDoSomething() {
if (!currentCoroutineContext().isActive) return
// ...
}

See also

for a function that throws an exception instead of returning a boolean value.


Returns true when the Job of the coroutine in this context is still active (has not completed and was not cancelled yet) or the context does not have a Job in it.

Check this property in long-running computation loops to support cancellation when CoroutineScope.isActive is not available:

while (coroutineContext.isActive) {
// do some computation
}

The coroutineContext.isActive expression is a shortcut for get(Job)?.isActive ?: true. See Job.isActive.