Junior — Middle
Kuidas erineb SupervisorJob tavalise Job-st korutinide ja ülesannete haldamise kontekstis?
sobes.tech AI
Vastus AI-lt
In Kotlin, Job in coroutines represents a task that can be canceled and is tracked in the coroutine hierarchy. 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 ends with an error, this error cancels the entire parent
Joband 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 work despite the error in the other
delay(1000)
println("Execution continues")
}
}
Using SupervisorJob is convenient when you want a failure of one task not to affect the execution of other parallel tasks.