In the kotlinx.coroutines
library you can start new coroutine using either launch
(with join
) or async
(with await
). What is the difference between them?
问题:
回答1:
launch
is used to fire and forget coroutine. It is like starting a new thread. If the code inside thelaunch
terminates with exception, then it is treated like uncaught exception in a thread -- usually printed to stderr in backend JVM applications and crashes Android applications.join
is used to wait for completion of the launched coroutine and it does not propagate its exception. However, a crashed child coroutine cancels its parent with the corresponding exception, too.async
is used to start a coroutine that computes some result. The result is represented by an instance ofDeferred
and you must useawait
on it. An uncaught exception inside theasync
code is stored inside the resultingDeferred
and is not delivered anywhere else, it will get silently dropped unless processed. You MUST NOT forget about the coroutine you’ve started with async.
回答2:
I find this guide https://github.com/Kotlin/kotlinx.coroutines/blob/master/coroutines-guide.md to be useful. I will quote the essential parts