'How to access lifecycleScope of the host fragment from a custom view?

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.

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.coroutineScopeor 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?



Solution 1:[1]

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
}

EDIT If you don't need to make your custom view lifecycle aware, you can also simply pass the scope to your custom view from the activity/fragment

fun setScope(lifecycleScope: CoroutineScope) {
    scope = lifecycleScope
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1