SupervisorJob in Kotlin coroutines?SupervisorJob is a special kind of job that allows child coroutines to fail independently without cancelling their siblings.
SupervisorJob differ from a regular Job in Kotlin?In a regular Job, if one child coroutine fails, all siblings are cancelled. With SupervisorJob, one child's failure does not affect others.
SupervisorJob in a coroutine scope?Use SupervisorJob when you want child coroutines to run independently so that failure in one does not stop others from running.
SupervisorJob?The parent coroutine does not get cancelled automatically when a child fails under SupervisorJob. It continues running.
SupervisorJob where one child fails but others continue.val supervisor = SupervisorJob()
val scope = CoroutineScope(Dispatchers.Default + supervisor)
scope.launch {
delay(100)
throw Exception("Child 1 failed")
}
scope.launch {
delay(200)
println("Child 2 completed")
}Output:<br>Child 2 completed
SupervisorJob allow in Kotlin coroutines?SupervisorJob allows child coroutines to fail independently without cancelling their siblings.
Job, what happens?Under a regular Job, failure in one child cancels all siblings.
SupervisorJob?SupervisorJob allows siblings to continue running even if one child fails.
SupervisorJob?You combine a dispatcher with SupervisorJob() to create the scope.
val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())
scope.launch { throw Exception("Fail") }
scope.launch { println("Hello") }With SupervisorJob, the second child prints "Hello" despite the first child's failure.
SupervisorJob helps manage failures in child coroutines.SupervisorJob and why you would do that.