Kotlin 协程中的 launch/join 和 async/await 有什么区别 [英] What is the difference between launch/join and async/await in Kotlin coroutines

查看:56
本文介绍了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 the launch 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 of Deferred and you must use await on it. An uncaught exception inside the async code is stored inside the resulting Deferred 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.

      这篇关于Kotlin 协程中的 launch/join 和 async/await 有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆