In a coroutine, I’m using the `coroutineScope {}` ...
# coroutines
s
In a coroutine, I’m using the
coroutineScope {}
, calling several async methods, and collecting the deferreds into a
MutableList<Deferred<Any>>
. Before the coroutine is over, I call
deferreds.awaitAll()
on the list. This isn’t actually necessary if I don’t care about the results, right? A parent suspend function won’t complete until all it’s children coroutines have completed, right?
👌 2
a
Yes, but now if you don't care about the results, you need to consider using using launch instead of async
s
So I don’t care about the actual results, but I do care if an exception is thrown. This is being done in a server request (ktor), and if there is an error doing any of the operations, I want it to bubble to the request and return an exception
I think launch would ignore the errors as well.
s
Would it though? Can you try making a repro in Kotlin playground to show when that would happen maybe?
s
I’m pretty sure the parent coroutine will succeed, even if the child coroutine fails.
🚫 1
This is just my understanding of the documentation from when I read it 5 years ago
the only way to get an exception from a launch is through an uncaught exception handler (I think)
j
I’m pretty sure the parent coroutine will succeed, even if the child coroutine fails.
Depends what sort of
Job
is in the parent coroutine's context.
launch would ignore the errors
It doesn't. But unlike
coroutineScope
, exceptions can't be caught by wrapping in
try-catch
. And depending on the
Job
in the
launch
-ed coroutine parent's context, failure may not propagate up the job hierarchy.
s
Depends what sort of
Job
is in the parent coroutine’s context.
What are the different types of
Job
for this?
j
A
SupervisorJob
will not fail or propagate failure up the job hierarchy when its children fail. Whereas, a regular
Job
will.
s
So I assumed the SupervisorJob would get the exception and then not fail, but you are saying it doesn’t even propogate?
j
By "propagate" I mean failing the jobs higher in the tree. Is that what you mean?
If you're also asking whether a
CoroutineExceptionHandler
at the root of the tree will respond to an exception thrown within a coroutine whose parent job is a
SupervisorJob
- it will. Here's code showing that using
supervisorScope
, and another using
SupervisorJob
directly.
g
So I don’t care about the actual results, but I do care if an exception is thrown
Because coroutineScope will rethrow exception, you are fine. If you want to catch it, just wrap coroutineScope with try/catch as any other suspend function And you almost never want supervisorScope on practice
s
When doing this, one needs to be careful to always re-throw CancellationException though right? (In case the try-catch you’re referring to catches wide enough to catch a CancellationException)
👍 2