0
0
KotlinConceptIntermediate · 3 min read

What is supervisorScope in Kotlin: Explanation and Example

supervisorScope in Kotlin is a special coroutine scope that lets child coroutines run independently so one failing child does not cancel others. It is useful when you want to handle errors in some children without stopping all coroutines inside the scope.
⚙️

How It Works

Imagine you have a group of friends working on different tasks together. If one friend stops working because of a problem, you don't want all the others to stop too. supervisorScope works like that group of friends. It lets each child coroutine run on its own, so if one fails, the others keep going.

Normally, in a coroutine scope, if one child coroutine throws an error, it cancels all siblings. But inside supervisorScope, the failure of one child does not affect the others. This helps you manage errors locally without stopping everything.

💻

Example

This example shows two child coroutines inside supervisorScope. One throws an error, but the other still completes successfully.

kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    supervisorScope {
        val child1 = launch {
            println("Child 1 starts")
            delay(100)
            throw RuntimeException("Child 1 failed")
        }
        val child2 = launch {
            println("Child 2 starts")
            delay(200)
            println("Child 2 completed")
        }
        child1.join()
        child2.join()
    }
    println("Supervisor scope finished")
}
Output
Child 1 starts Child 2 starts Child 2 completed Exception in thread "main" java.lang.RuntimeException: Child 1 failed at ... Supervisor scope finished
🎯

When to Use

Use supervisorScope when you want to run multiple tasks concurrently but don't want one failure to stop all tasks. For example, if you are loading data from several sources and one source fails, you may still want to process the others.

It is also helpful in UI apps where you want to handle errors in some background jobs without crashing the whole app or cancelling unrelated work.

Key Points

  • Independent children: Child coroutines run independently inside supervisorScope.
  • Error isolation: Failure in one child does not cancel siblings.
  • Use for fault tolerance: Helps keep other tasks running despite errors.
  • Part of Kotlin coroutines: Requires kotlinx.coroutines library.

Key Takeaways

supervisorScope isolates child coroutine failures so others keep running.
It is useful when you want to handle errors locally without cancelling all tasks.
Child coroutines inside supervisorScope run independently.
Use it to improve fault tolerance in concurrent Kotlin programs.