lifecycleScope.launch 与 onViewCreated 中的协程

lifecycleScope.launch vs coroutine inside onViewCreated

在此示例代码中:

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

            }
        }
    }
}

whenStarted 中的代码仅在片段的生命周期开始时获得 运行。我不清楚这到底是做什么的,而不是仅仅在 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 {} 的更详细的形式。如您所料,传入 launchWhenStarted 的 lambda 将暂停,直到 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 操作。