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 应用程序崩溃.加入
用于等待启动的协程完成,并且不会传播其异常.但是,崩溃的子协程也会取消其父协程并产生相应的异常.-
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
用于启动计算某些结果的协程.结果由Deferred
并且你必须使用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.
-