Sobes.tech
Junior — Middle

How does SupervisorJob differ from a regular Job in the context of coroutines and task management?

sobes.tech AI

Answer from AI

In Kotlin coroutines, Job represents a task that can be canceled and is tracked within a hierarchy of coroutines. SupervisorJob is a special type of Job that differs in behavior when exceptions occur in child coroutines.

Main difference:

  • Job: If one of the child coroutines fails with an error, this error cancels the entire parent Job and all other child coroutines.
  • SupervisorJob: An error in one child coroutine does not cancel other child coroutines or the parent Job. This allows isolating errors and continuing execution of other tasks.

Example:

val supervisor = SupervisorJob()
val scope = CoroutineScope(Dispatchers.Default + supervisor)

scope.launch {
    launch {
        // This coroutine will fail with an exception
        throw Exception("Error in child coroutine")
    }
    launch {
        // This coroutine will continue to run despite the error in the other
        delay(1000)
        println("Execution continues")
    }
}

Using SupervisorJob is convenient when you want a failure in one task not to affect the execution of other parallel tasks.