Creates a supervisor job object in an active state...
# coroutines
v
Creates a supervisor job object in an active state. Children of a supervisor job can fail independently of each other Found the above statement on the doc of supervisor job, It is quite confusing for me. Like the supervisor job is used in the context of child coroutine. "Children of a supervisor job" where in practice we use a supervisor job on the child coroutine
s
When a (parent) coroutine is configured with a plain Job, any cancelled child-coroutine (or one that threw an exception) will cancel/end its parent coroutine and therefore all the other child-coroutines as well. When configured with a SupervisorJob, only the cancelled/failing child-coroutine will end. The parent coroutine (and therefore its sibling coroutines) will keep running.
v
Agree but the first line "children of supervisor job" does it indicate like scope.launch(SupervisorJob()){ child coroutine 1 child coroutine 2 }
j
You're not really supposed to pass jobs to launch this way
s
scope = CoroutineScope(SupervisorJob()) scope.launch { ... }
j
Yeah, or:
Copy code
supervisorScope {
    launch { ... }
    launch { ... }
}
s
@Joffrey yup, The "supervisorScope { ... }" can be used in place of "coroutineScope { ...}", when you need access to the outer CoroutineScope inside a 'suspend fun' but with a SupervisorJob. The "CoroutineScope(SupervisorJob())" is for launching a brand new top Coroutine.
v
Agree @Joffrey and @streetsofboston, but i was talking about the doc statement where they have mentioned "children of supervisor job" but in practice we use a supervisor job on children. The statement is a bit confusing for me
j
The doc is accurate. When you create a supervisor scope (or coroutine scope with a supervisor job), that job acts as a parent for the jobs of the nested coroutines. When you use
scope.launch {...}
, it creates a child job of the job that's in the scope.
In practice we use a supervisor job on children
Not really. What makes you say that? It's very uncommon to write
launch(SupervisorJob())
because that would break structured concurrency
v
For example: val scope = CoroutineScope(Dispatcher.IO) scope.launch{ launch(SupervisorJob()){ } } Here the inner launch is our child so I was thinking of using a SupervisorJob on it..
j
But you shouldn't do that. Adding a job like this breaks structured concurrency with the parent coroutines. What are you trying to achieve here?
v
I was trying on a sample code.. Understood... 👍 Thanks @Joffrey