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.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?
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.
Then inside the custom view, I used it like:
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