【问题标题】:How to access lifecycleScope of the host fragment from a custom view?如何从自定义视图访问宿主片段的生命周期范围?
【发布时间】:2021-01-10 18:09:35
【问题描述】:
我需要在自定义视图中使用协程。看了这个talk,我相信我最好的选择是使用lifecycleScope作为协程作用域,这样在生命周期所有者被销毁时会自动取消。
但是,我似乎无法访问自定义视图中的生命周期范围。根据documentation,我们可以通过lifecycle.coroutineScope 的生命周期 对象或lifecycleOwner.lifecycleScope 的lifecycleOwner 对象访问它。但是自定义视图不是生命周期所有者。那么我可以以某种方式访问片段的生命周期范围吗?或者如果我不能,我应该使用哪个协程上下文?
【问题讨论】:
标签:
android
android-custom-view
kotlin-coroutines
coroutinescope
【解决方案1】:
我通过实现LifecycleObserver 接口解决了这个问题。在free course on Udacity 的第 4 课中很好地解释了如何使用 LifecycleObserver 接口制作生命周期感知组件。
我在片段和自定义视图中注册了片段的生命周期,当我得到生命周期时,我使用生命周期来获取生命周期范围。
//Inside custom view
fun registerLifecycleOwner(lifecycle: Lifecycle){
lifecycle.addObserver(this)
scope = lifecycle.coroutineScope
}
//Inside fragment
binding.myCustomView.registerLifecycleOwner(lifecycle)
然后在自定义视图中,我像这样使用它:
scope.launch{
//Do work
}