Kotlin协程中launch/join和async/await有什么区别
在kotlinx.coroutines
库中,您可以使用launch
(带有join
)或async
(带有await
)启动新协程.它们之间有什么区别?
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?
-
launch
用于射击并忘记协程.这就像启动一个新线程.如果launch
中的代码以异常终止,则将其视为线程中的未捕获异常-通常在后端JVM应用程序中打印到stderr并使Android应用程序崩溃.join
用于等待启动的协程的完成,并且不会传播其异常.但是,崩溃的 child 协程也将其父级与相应的异常取消.-
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
用于启动协程以计算结果.结果由await
放在上面.async
代码中未捕获的异常存储在结果Deferred
中,并且未在其他任何地方传递,除非进行处理,否则它将被静默删除. 您一定不要忘记从异步开始的协程.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.
-