https://developer.android.com/topic/libraries/architecture/lifecycle#implementing-lco
The docs say that Fragments and Activities in Support Library 26.1.0 and later already implement the LifecycleOwner interface.
This is greatly useful if we can use the LifecycleOwner of the activity or fragment to register LiveData objects or have it call our methods annotated with
@OnLifecycleEvent(Lifecycle.Event.ON_START)
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
etc
in our custom classes.
But we also have the option to implement a custom LifecycleOwner. Under what circumstances does it make sense to have a custom LifecycleOwner, considering that it will complicate things because now we have to manually track the lifecycle events like:
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
etc
?
I think I can answer this question myself, the use case where having a custom
LifecycleOwner
makes sense to be used is if you have an atypical lifecycle meaning a different lifecycle than the one activities and fragments have.I had to use fragments to load ads on the lockscreen of the phone, and that meant that the ad would have to be loaded when the phone's screen was off and the user would see the ad when he'd press the power on button of the phone and turn on the display.
This behavior is important: the ad has to be loaded in background (screen off) and when the user turns the screen on, the ad is there for the user to see it.
Performing fragment transaction when the screen is off meant that the transaction would happen after the
onStop()
of the activity is called and that is possible only using thecommitAllowingStateLoss()
.Also the data that was to be passed as arguments to the fragments had to be and could be updated when the screen was off as well, that means again when the activity is in the stopped state.
So I had to create a custom
LifecycleOwner
to be used with aLiveData
object that would observe changes of the data that was supposed to be passed to the fragments.This custom
LifecycleOwner
implementation would ignore the stopped state of the activity and that way theLiveData
could react to changes of data even while the activity was in stopped state.