android - LifecycleScope.launch 与 onViewCreated 中的协程

标签 android kotlin-coroutines

在此示例代码中:

class MyFragment: Fragment {
    init {
        lifecycleScope.launch {
            whenStarted {

            }
        }
    }
}

whenStarted 中的代码仅在 fragment 的生命周期开始时运行。我不清楚这到底是做什么的,而不是仅仅在 onViewCreated 内部启动一个协程。文档状态:

If the Lifecycle is destroyed while a coroutine is active via one of the when methods, the coroutine is automatically canceled.



那么这是您使用lifecycleScope.launch 的唯一原因吗?如果生命周期终止,让协程自动终止?

最佳答案

lifecycleScope是由 SupervisorJob 管理的范围其生命周期与 Fragment 相关联的生命周期。所以只需使用 lifecycleScope当底层 Lifecycle 时,您的协程将被取消实例(在这种情况下为 FragmentLifecycleRegistry)被销毁。

我相信lifecycleScope.launch { whenStarted {}}lifecycleScope.launchWhenStarted {} 的更详细的形式.如您所料,lambda 传递到 launchWhenStarted将暂停直到 Fragment处于启动状态。

So is that the only reason why you would use lifecycleScope.launch? To have the coroutine automatically terminated if the lifecycle gets terminated?



取消是好处之一。另一个好处是 lifecycleScope.launch使用 MainDispatcher默认情况下(与默认使用 Dispatches.Default 的其他构建器不同),因此它保证使用它启动的协程可以执行 UI 操作。

关于android - LifecycleScope.launch 与 onViewCreated 中的协程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59718077/

相关文章:

android - 无法访问类 CoroutineScope。检查模块类路径

android - 如何在android map 中勾勒出文字轮廓

android - 多个 fragment 的 TreeView

android-studio - 不必放置值2>值1

java.lang.VerifyError 尝试运行时需要精确引用阻止 Kotlin 在 Android 中暂停乐趣

multithreading - 强制挂起的函数在一个线程上工作以在后台映射 Realm 对象

android - 如何在 android 中显示没有标签或街道名称的谷歌地图?

android - Android 应用程序的 SQLite 架构

android - 如何初始化ViewBinding?

Android EditText 协程去抖操作符,如 RxJava