Home > OS >  With LiveData observeForever what happen to the observer when the MainActivity is closed?
With LiveData observeForever what happen to the observer when the MainActivity is closed?

Time:12-06

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)?

CodePudding user response:

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()).

  • Related