0

I have a service where I declare this liveData

public static final MutableLiveData<String> newMessageDispatcher = new MutableLiveData<>();

Inside the main activity I cannot do newMessageDispatcher.observe(myActivity, newMessageObserver) because my activity do not extends AppCompatActivity so it's not a LifecycleOwner.

Now If I do newMessageDispatcher.observeForever(newMessageObserver), what will happen when the user will close the app (by swiping up in the recent apps window), so closing the main activity without calling newMessageDispatcher.removeObserve(newMessageObserver)? Does the observer will be successfully removed or do I absolutely need to call newMessageDispatcher.removeObserve(newMessageObserver)?

zeus
  • 12,173
  • 9
  • 63
  • 184

1 Answers1

2

because my activity do not extends AppCompatActivity so it's not a LifecycleOwner.

You need to extend ComponentActivity to get LifecycleOwner. Or, you could implement LifecycleOwner logic yourself, if you wanted.

what will happen when the user will close the app (by swiping up in the recent apps window), so closing the main activity without calling newMessageDispatcher.removeObserve(newMessageObserver)?

The precise behavior of that, or even if that behavior exists, will vary across the tens of thousands of Android device models.

Does the observer will be successfully removed

You should not assume that it will.

or do I absolutely need to call newMessageDispatcher.removeObserve(newMessageObserver)?

That would be a good idea. Do it in the counterpart lifecycle method to where you are calling addObserver() (e.g., if you call addObserver() in onCreate(), call removeObserver() in onDestroy()).

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • thanks @CommonsWare. but when the user close the app by swiping up in the recent apps window, the app will be suddenly closed and no ondestroy or anythink else will be called :( do you know how I can implement the LifecycleOwner myself ? – zeus Dec 05 '22 at 17:03
  • @zeus: "but when the user close the app by swiping up in the recent apps window, the app will be suddenly closed and no ondestroy or anythink else will be called" -- again, the behavior will vary by device model. If your process is terminated, then there is no need to unregister the observer, as the observer and the thing that it is observing is all gone. You could also call `addObserver()` in a different lifecycle method (e.g., `onPause()`) and `removeObserver()` in the counterpart (e.g,. `onResume()`). – CommonsWare Dec 05 '22 at 17:06
  • "do you know how I can implement the LifecycleOwner myself ?" -- while it is in the context of a different problem, [this gist](https://gist.github.com/handstandsam/6ecff2f39da72c0b38c07aa80bbb5a2f) should give you some direction. – CommonsWare Dec 05 '22 at 17:08