I have a question about `SupervisorJob`. This code...
# coroutines
s
I have a question about
SupervisorJob
. This code
Copy code
CoroutineScope(SupervisorJob()).launch {
    launch { 
        println("Launched Child 1")
        delay(500)
        println("Child 1 crashed")
        throw SillyException()
    }

    launch {
        println("Launched Child 2")
        delay(1000)
        println("Child 2 is still running")
        delay(500)
    }

    delay(1000)
    println("Parent is still running")
}

Thread.sleep(2000)
prints out this:
Copy code
Launched Child 1
Launched Child 2
Child 1 crashed
Exception in thread "DefaultDispatcher-worker-2 @coroutine#3" launch_exceptions.SillyException: Silly
	at launch_exceptions.FileKt$main$1$1.invokeSuspend(File.kt:20)
        ...
I expected only “Child 1” to crash/stop, due to the parent being a Supervisor-Job . However, I expected “Child 2" launch and the parent to continue running… especially since
MainScope()
is defined in a similar way…
e
inner
launch
is start as child for outer
launch
, which is not a
SupervisorJob
. Only childs of
CoroutineScope(SupervisorJob())
fails independently from each other
s
I see. Thank you, @Evgeniy Zaharov ! You say that this would work:
Copy code
val scope = CoroutineScope(SupervisorJob())
scope.launch { 
    println("Launched Child 1")
    delay(500)
    println("Child 1 crashed")
    throw SillyException()
}

scope.launch {
    println("Launched Child 2")
    delay(1000)
    println("Child 2 is still running")
    delay(500)
}
l
You could use
supervisorScope { … }
also, and launch all the coroutines here.
s
Thanks! But not always, though. The function
supervisorScope
is a
suspend
fun and can’t be called from a regular non-suspending function.
But it is a handy function to move a sub-tree of your coroutine scope’s children within a SupervisorJob. 🙂
d
Perhaps it would work if you used the coroutine context parameter instead of the scope