Hi guys, I have a question. I know that when you l...
# coroutines
a
Hi guys, I have a question. I know that when you launch coroutines, Kotlin is nice enough that wants to keep structured concurrency such that if a coroutine in a context fails, than all the running coroutines gets cancelled.
Copy code
runBlocking {
  launch { dosomething }
  launch { throw Exception }
}
This is nice because it make your thinking easier, and you are pretty much saying: here’s all I need to do, do that in parallel and in case something happens fail everything. Now my question is this: what if I want to launch many coroutines that are independent from each other? I take the example of threadpool when on many threads you launch some operation but one thread throwing exception does not affect the others. Imagine that on each coroutine I’m handling a separate http request for example. From the official doc, apart from handling explicitly the exception handling, I haven’t seen any of such examples and I wonder: is the price of launching coroutines that easy paid off when you really want to go in parallel with no noisy neighbours?
maybe I can answer myself saying that I should be doing something like this
Copy code
runBlocking {
  coroutineScope { launch { dosomething }}
  coroutineScope { launch { throw Exception } }
}
and this isolates the scope of the different coroutines but still make them running on the same dispatcher/context
z
CoroutineScope will not return until all child coroutines have completed, so this is actually less concurrent than your original code.
If you want your launch coroutines to outlive the current scope, you need to explicitly provide another scope to launch them in.
a
right! would that make them independent from an exception handling point of view?
z
Independent of the current scope, yes.
If you want one coroutine's failure to not cancel its siblings, use SupervisorJob/supervisorScope
☝🏻 1
👍 4