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

后端 未结 3 557
渐次进展
渐次进展 2021-01-01 11:10

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

This is the constructor:

public MyObserver(AppCompatActivity a         


        
3条回答
  •  说谎
    说谎 (楼主)
    2021-01-01 11:25

    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.

提交回复
热议问题