如何从自定义视图访问宿主片段的生命周期范围? [英] How to access lifecycleScope of the host fragment from a custom view?
问题描述
我需要在自定义视图中使用协程.看完这个谈话后,我相信我最好的选择是使用 lifecycleScope 作为协程范围,这样当生命周期所有者被销毁时它会自动取消.
I need to use coroutines inside a custom view. After watching this talk, I believe my best option is to use lifecycleScope as the coroutine scope, so that it will be automatically cancelled when lifecycleowner is destroyed.
但是我似乎无法访问自定义视图中的生命周期范围.根据文档,我们可以从lifecycle 对象为 lifecycle.coroutineScope
或来自 lifecycleOwner 为 lifecycleOwner.lifecycleScope
.但是自定义视图不是生命周期所有者.那么我可以以某种方式访问片段的生命周期范围吗?或者如果我不能,我应该使用哪个协程上下文?
However I don't seem to have access to lifecycleScope inside the custom view. According to documentation, we can either have access to it from a lifecycle object as lifecycle.coroutineScope
or from a lifecycleOwner as lifecycleOwner.lifecycleScope
. But custom view is not a lifecycle owner. So can I have access to lifecycleScope of the fragment somehow? Or if I can't, which coroutine context should I use instead?
推荐答案
我通过实施 LifecycleObserver 接口.这在 Udacity 上的 免费课程的第 4 课中得到了很好的解释 如何使用 LifecycleObserver 接口制作生命周期感知组件.
I solved this by implementing LifecycleObserver interface. It was very well explained in lesson 4 of this free course on Udacity how to make lifecycle aware components with LifecycleObserver interface.
我在片段内部和自定义视图中注册了片段的生命周期,在获取生命周期的同时,我使用生命周期来获取生命周期范围.
I registered the lifecycle of the fragment inside the fragment and inside the custom view, while I get the lifecycle, I used the lifecycle to grap lifecycleScope.
//Inside custom view
fun registerLifecycleOwner(lifecycle: Lifecycle){
lifecycle.addObserver(this)
scope = lifecycle.coroutineScope
}
//Inside fragment
binding.myCustomView.registerLifecycleOwner(lifecycle)
然后在自定义视图中,我像这样使用它:
Then inside the custom view, I used it like:
scope.launch{
//Do work
}
这篇关于如何从自定义视图访问宿主片段的生命周期范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!