34

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?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
esilver
  • 27,713
  • 23
  • 122
  • 168

3 Answers3

42

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.

TareK Khoury
  • 12,721
  • 16
  • 55
  • 78
8

TL;DR: You're better off explicitly removing the observer when you are done with it, or use something that handles this automatically, such as LiveData.

Lifecycle is an abstract class. So, technically, you have no idea what the implementation is and what the rules of the game are.

The one concrete Lifecycle is LifecycleRegistry. It has strong references to the observers. So now you are counting on the LifecycleRegistry being garbage-collected in a timely fashion, such as when the activity is destroyed. For FragmentActivity, that appears to be the case. So in practice, for the now-current version of all this stuff, you could get away without unregistering the observer and suffer few ill effects, if any.

But that's not part of the Lifecycle contract. Arguably, any decent implementation of Lifecycle (or things that use LifecycleRegistry) should cleanly handle the case where you fail to unregister... but I wouldn't risk it.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • 1
    If you're registering observers for components that clearly have a different (shorter) lifecycle than the Activity, you should unregister appropriately. This is becoming a more common scenario than people realize, especially in the world of single activity apps. – Daniel Robertson Nov 05 '19 at 17:47
1

I'm using LifecycleRegistry in a singleton object that manages audio sounds. After adding LeakCanary it detected a memory leak because of this issue.

However, calling removeObserver, the memory leak never appeared again.

So it may be true that when using LiveData + LifecycleRegistry you don't need to unregister. But if it's a custom component using LifecycleRegistry, my experience shows that calling removeObserver is a must to avoid memory leaks.

Vito Valov
  • 1,765
  • 1
  • 19
  • 37