Another thing which I find a bit puzzling is that ...
# coroutines
a
Another thing which I find a bit puzzling is that I have a class like this:
Copy code
class MyClass : CoroutineScope {

    override val coroutineContext = Dispatchers.Default + SupervisorJob()

    fun doSomething(): Job {
        val handler = CoroutineExceptionHandler { _, exception ->
            // ...
        }
        return launch(handler) {
            // ...
        }
    }
}
what I want to achieve is that child jobs (launched with
launch
) can fail independently. This works right now but it also works if I remove
+ SupervisorJob()
The docs say that if I add a
CoroutineExceptionHandler
to a coroutine it won't bubble exceptions up which is fine but in
SupervisorJob
I can see this:
Copy code
A failure or cancellation of a child does not cause the supervisor job to fail and does not affect its other children,
so a supervisor can implement a custom policy for handling failures of its children:

A failure of a child job that was created using [launch][CoroutineScope.launch] can be handled via [CoroutineExceptionHandler] in the context.
so it implies that I can only use
CoroutineExceptionHandler
in a
SupervisorJob
yet it works without one. Did I miss something?
a
you still need
SupervisorJob
a
no it works without
SupervisorJob
I've just written an integration test
if I add the
handler
to
launch
and there is a failure
the
handler
is called and the parent (
MyClass
here) is not cancelled
but this is written in the docs so it is OK
I'm just puzzled because in the docs of
SupervisorJob
it says that I need to use it to have a
Job
which is not cancelled if a child fails but apparently this is not the case
so I'm wondering whether I miss something or there is some edge case if I don't use
SupervisorJob
d
Yes, it works in the absence of a
SupervisorJob
, it does not work in the presence of a regular
Job()
. The documentation isn't explicit about this, but I don't see it stating that
CoroutineExceptionHandler
works exclusively with
SupervisorJob
.
a
nice, thanks!
a
@addamsson
CoroutineExceptionHandler
will work with regular
Job
, but the key difference is that
Job
will fail after error occurs. Please check - https://github.com/Kotlin/kotlinx.coroutines/issues/996#issuecomment-472789627
a
I'm using a
CoroutineContext
and I
launch
child jobs with `CoroutineExceptionHandler`s and the parent job is not failing when a child fails. What you're saying is that an error happens in the parent itself it will get cancelled, but if I add
SupervisorJob
to it then it will not, right?
a
@addamsson doc:
Copy code
The most basic instances of [Job] are created with [launch][CoroutineScope.launch] coroutine builder or with a `Job()` factory function. By default, a failure of any of the job's children leads to an immediately failure
of its parent and cancellation of the rest of its children. This behavior can be customized using [SupervisorJob].
a
It does not work that way
I have a test to prove it