Search code examples
androidandroid-lifecycleactivity-lifecycle

Is it mandatory to remove yourself as an observer from Android Lifecycle?


I am building an Android Java class which implements the LifecycleObserver interface.

This is the constructor:

public MyObserver(AppCompatActivity activity) {
    this.mActivity = new WeakReference<AppCompatActivity>(activity);
    activity.getLifecycle().addObserver(this);
}

Is it necessary to ever call removeObserver, using something like:

@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void destroyListener() {
    if (this.mActivity.get() != null) {
        this.mActivity.get().getLifecycle().removeObserver(this);
    }
}

Or, can I observe forever?


Solution

  • TL;DR: Nope.

    According to this link here, where a user asked your question on the android-lifecycles Github repo. The answer of a Google developer to this questions was:

    Yes, that's the whole point of the new lifecycle-aware components, no need to unsubscribe/remove observers.