Skip to main content

Coroutine scope vs Supervisor scope

Published 2 min readMarkdown
Coroutine scope vs Supervisor scope
  • Coroutine scope : default behavior (launch in coroutineScope or runBlocking). If one child fails, it cancels the entire scope — all other siblings are canceled too.

  • Supervisor scope: failure in one child won’t cancel the other children.

Coroutine scope :

import kotlinx.coroutines.*

fun main() = runBlocking {
    val handler = CoroutineExceptionHandler { _, exception ->
        println("Caught by handler: $exception")
    }
    val scope = CoroutineScope(SupervisorJob()+ handler)

    scope.launch {
        launch {
            println("Child 1 starts")
            throw RuntimeException("Child 1 failed!")
        }
        launch {
            delay(500)
            println("Child 2 still runs")
        }
    }.join()

    println("Done")
}

Output:
Child 1 starts
Caught by handler: java.lang.RuntimeException: Child 1 failed!
Done

Here , child 2 doesn’t run as it is coroutine scope and cancels other children.

Supervisor scope :

fun main() = runBlocking {
    val handler = CoroutineExceptionHandler { _, exception ->
        println("Caught by handler: $exception")
    }
    val scope = CoroutineScope(SupervisorJob()+ handler)

    supervisorScope {
        launch(handler) {
            println("Child 1 starts")
            throw RuntimeException("Child 1 failed!")
        }
        launch(handler) {
            delay(500)
            println("Child 2 still runs")
        }
    }.join()

    println("Done")
}
Output:
Child 1 starts
Caught by handler: java.lang.RuntimeException: Child 1 failed!
Child 2 still runs
Done

Here , all children run regardless of one getting cancelled as that is the use of supervisor scope.

Another way of calling supervisor scope:

fun main() = runBlocking {
    val handler = CoroutineExceptionHandler { _, exception ->
        println("Caught by handler: $exception")
    }
    val scope = CoroutineScope(SupervisorJob()+ handler)

    val supJob1 =  scope.launch {
            println("Child 1 starts")
            throw RuntimeException("Child 1 failed!")
        }

    val supJob2 =  scope.launch(handler) {
            delay(500)
            println("Child 2 still runs")
        }

    joinAll(supJob1, supJob2)
    println("Done")
}
Output:
Child 1 starts
Caught by handler: java.lang.RuntimeException: Child 1 failed!
Child 2 still runs
Done

Here we are using scope.launch instead of supervisorjob to get the same output.

This is it for the difference between normal scope and supervisor scope. See you soon in the next article !!!

No comments yet. Be the first to comment.