0
0
Kotlinprogramming~7 mins

SupervisorJob for independent failure in Kotlin

Choose your learning style9 modes available
Introduction

SupervisorJob lets child tasks fail without stopping their siblings. It helps keep other tasks running even if one fails.

When you want multiple tasks to run independently and not cancel each other on failure.
When handling multiple network requests where one failure shouldn't stop others.
When running background jobs that should continue even if one crashes.
When you want to isolate errors in concurrent operations.
When building resilient apps that recover from partial failures.
Syntax
Kotlin
val supervisor = SupervisorJob()
val scope = CoroutineScope(Dispatchers.Default + supervisor)

SupervisorJob is used as a parent job to allow independent failure of child coroutines.

Combine SupervisorJob with a CoroutineScope to launch child coroutines.

Examples
Creates a supervisor job and launches two child coroutines that run independently.
Kotlin
val supervisor = SupervisorJob()
val scope = CoroutineScope(Dispatchers.Default + supervisor)

scope.launch {
    // child coroutine 1
}

scope.launch {
    // child coroutine 2
}
Even if child 1 fails, child 2 continues and prints its message.
Kotlin
val supervisor = SupervisorJob()
val scope = CoroutineScope(Dispatchers.Default + supervisor)

scope.launch {
    throw Exception("Fail child 1")
}

scope.launch {
    delay(1000)
    println("Child 2 completed")
}
Sample Program

This program shows two child coroutines launched under a SupervisorJob. Child 1 throws an exception, but child 2 still completes and prints its message.

Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    val supervisor = SupervisorJob()
    val scope = CoroutineScope(Dispatchers.Default + supervisor)

    scope.launch {
        println("Child 1 starts")
        throw Exception("Child 1 failed")
    }

    scope.launch {
        delay(500)
        println("Child 2 completed")
    }

    delay(1000) // wait for children
}
OutputSuccess
Important Notes

Without SupervisorJob, if one child fails, all siblings get cancelled.

SupervisorJob helps build fault-tolerant concurrent code.

Always handle exceptions in child coroutines to avoid silent failures.

Summary

SupervisorJob allows child coroutines to fail independently.

It prevents one failure from cancelling all sibling coroutines.

Use it to build more resilient concurrent programs.