1

doesn't "Global.async{}" do the same things that "Global.launch{}" does and more? If yes, then why did they invent "Global.launch{}"? please provide a solid situation if possible.

I already searched a lot, but didn't find a convincing answer.

Ahmed Eid
  • 61
  • 6
  • Does this answer your question? [What is the difference between launch/join and async/await in Kotlin coroutines](https://stackoverflow.com/questions/46226518/what-is-the-difference-between-launch-join-and-async-await-in-kotlin-coroutines) – Jeff Bowman Nov 18 '22 at 10:31

1 Answers1

3

To address the obvious difference: async coroutines can return a value, whereas launch coroutines can't. I guess you know this, and are asking if launch does anything that can't be done with an async coroutine that returns Unit.

The primary difference between async and launch is the way they handle errors when launched as root coroutines. A root coroutine is a coroutine that is launched directly in a root scope, rather than as a child of an existing coroutine.

When you create a root coroutine with launch, exceptions are propagated to the scope's UncaughtExceptionHandler, if it has one. This is because the error would otherwise be lost. The job doesn't return a result, so there's nowhere else in the code that would be able to handle the error.

However, when you create a root coroutine with async, exceptions are caught and contained in the resulting Deferred object. The exception is thrown when you call await. It doesn't propagate to the UncaughtExceptionHandler. This is because we expect that some other code will eventually await the result of the job and handle the error.

This distinction only applies to root coroutines. When you start a coroutine as a child of an existing coroutine, errors are always propagated to the parent job, regardless of whether the coroutine was started with async or launch.

So, to answer your question, launch provides the additional capability to handle errors with an UncaughtExceptionHandler when launching root coroutines.

Sam
  • 8,330
  • 2
  • 26
  • 51
  • Thanks Sam, you clarified it more for me. I read the answer in this link https://stackoverflow.com/questions/46226518/what-is-the-difference-between-launch-join-and-async-await-in-kotlin-coroutines as Alex.T and Jeff Bowman pointed out and I found it very useful but you clarified it more. Thanks. – Ahmed Eid Nov 18 '22 at 10:57
  • 2
    It's worth mentioning that Roman's answer to the linked question is out-of-date, thanks to the introduction (by him, ironically) of structured concurrency. In his answer he says that an uncaught exception inside an `async` coroutine is always dropped unless you `await` it. In fact, that's no longer true for coroutines launched as a child of an existing coroutine. In that case, a failed `async` job will still cause its parent job to fail. Roman's original answer is still true for root coroutines, though. – Sam Nov 18 '22 at 11:02