Is it imperative to film myself as an observer from the Android life cycle?

I am creating an Android Java class that implements an interface . LifecycleObserver

This is the constructor:

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

Do I ever need to call using something like: removeObserver

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

Or can I watch forever?

+9
source share
3 answers

TL DR: Nope.

This link is here where the user asked his question about the android-lifecyclesGithub repo. The answer of the Google developer to these questions was:

Yes, that the whole point of the new components, taking into account the life cycle, there is no need to unsubscribe / delete observers.

+10
source

TL; DR: , , , , LiveData.

Lifecycle abstract. , , .

Lifecycle LifecycleRegistry. . , , LifecycleRegistry , , . FragmentActivity . , , , , , .

Lifecycle. , Lifecycle ( , LifecycleRegistry) , ... .

+2

LifecycleRegistry , . LeakCanary - .

, removeObserver, .

Thus, it may be true that when using LiveData + LifecycleRegistry you do not need to unregister. But if this is a custom component using LifecycleRegistry, my experience shows that the call to removeObserver is mandatory to avoid memory leaks.

0
source

Source: https://habr.com/ru/post/1690274/


All Articles