I am building an Android Java class which implements the LifecycleObserver interface.
This is the constructor:
public MyObserver(AppCompatActivity a
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.