Would it be correct to say that this code: `withCo...
# coroutines
c
Would it be correct to say that this code:
Copy code
withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
  foo()
}
is conceptually equivalent as this one:
Copy code
launch(<http://Dispatchers.IO|Dispatchers.IO>) {
  foo()
}.join()
Since the implementation is very different, I expect that for performance reasons it does something else, but as a developer should I use
withContext
as syntax sugar for
launch().join()
, or is there something else I need to know about?
l
@CLOVIS if the second one crashes, it will cancel the parent scope, and have the
Throwable
propagate up the scopes until caught, while the former will just throw from its call site.
c
Really good to know, thanks!
s
Would the top one not also cancel the parent scope? If not, why not? That must also have started at some point with
launch() { // }
as well. I don't really understand the exact differences there.
l
@Stylianos Gakis If the top one is surrounded with a
try
catch
block, it'll not crash the scope, while for the second one, the scope will crash (cancelling any other childs, the siblings of the crashed coroutines) and propagate the exception anyway.
s
Aha, so even if the bottom option is also surrounded with try catch on the call site, it will still crash since it's inside a different job (? or what would that be called?) it will crash and propagate up. Thanks for the clarification!
l
The second option launches a child job. By crash, I mean throwing something other than a
CancellationException
that is uncaught in that
launch { … }
call.