Search code examples
androidandroid-architecture-componentsandroid-architecture-lifecycle

Holding reference of Lifecycle object in LifecycleObserver


In the LifecycleObserver class how good is it a practice to hold the reference of Lifecycle object? What complication can arise?

class MyLocationListener implements LifecycleObserver {
    private Lifecycle mLifecycle;
    public MyLocationListener(Context context, Lifecycle lifecycle, Callback callback) {
           mLifecycle = lifecycle  
           ...
    }
}

Solution

  • You should not keep a reference it is an opening for memory leaks the Observer needs to observe not to contain the reference and if you want to perform actions on lifecycle changes do it like so:

     @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY //you can change to whatever lifecycle event you need)
     public void activityDestroied() {
     //actions here
     }