isActive
Returns true
when the current Job is still active (has not completed and was not cancelled yet).
Coroutine cancallation 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.
The isActive property is inteded to be used for scenarios like this:
val watchdogDispatcher = Dispatchers.IO.limitParallelism(1)
fun backgroundWork() {
println("Doing bookkeeping in the background in a non-suspending manner")
Thread.sleep(100L) // Sleep 100ms
}
// Part of some non-trivial CoroutineScope-confined lifecycle
launch(watchdogDispatcher) {
while (isActive) {
// Repetitively do some background work that is non-suspending
backgroundWork()
}
}
This function returns true
if there is no job in the scope's coroutineContext. This property is a shortcut for coroutineContext.isActive
in the scope when CoroutineScope is available. See coroutineContext, isActive and Job.isActive.
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.