在此示例代码中:
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
时,您的协程将被取消实例(在这种情况下为 Fragment
的 LifecycleRegistry
)被销毁。
我相信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/