Architecture Components: Observer Keep Observing Even After Removing It on Ondestroy

Architecture components: Observer keep observing even after removing it on onDestroy

So what we learned from experiments in the comments, you needed to check if mTablesData is already being observed before observing it, and observe only if it is not being observed, like

if (!mTablesData.hasObservers()) {
mTablesData.observeForever(tablesModels -> {
...

Do I need to call removeObserver for lifecycle, upon its onDestroy() event?

There is one chain of discussion over github related this topic.

as far as I know, no need to call removeObserve explicitly.

The only reason is lifecycle-aware components are specifically design to make sure this callbacks.

Hear is the link you can refer, https://github.com/googlecodelabs/android-lifecycles/issues/5

LiveData remove Observer after first callback

Your first one will not work, because observeForever() is not tied to any LifecycleOwner.

Your second one will not work, because you are not passing the existing registered observer to removeObserver().

You first need to settle on whether you are using LiveData with a LifecycleOwner (your activity) or not. My assumption is that you should be using a LifecycleOwner. In that case, use:

Observer observer = new Observer<DownloadItem>() {
@Override
public void onChanged(@Nullable DownloadItem downloadItem) {
if(downloadItem!= null) {
DownloadManager.this.downloadManagerListener.onDownloadManagerFailed(null, "this item already exists");
return;
}
startDownload();
model.getDownloadByContentId(contentId).removeObservers((AppCompatActivity)context);
}
};

model.getDownloadByContentId(contentId).observe((AppCompatActivity)context, observer);

Fragment. getViewLifeCycleOwner doesn't prevent multiple calls of LiveData Observer

It's because of how Fragment Lifecycle works. When you move to and fro from a fragment onViewCreated() is called again. In onViewCreated you're calling viewModel.getProfileLive() which returns the livedata upto from the repository and observe to it.

Since onViewCreated() gets called everytime when you move back to the Fragment so is your call to viewModel.getProfileLive() and in turn the repository gets called again which again triggers the observe method in your Fragment.

In order to solve this problem,
create a LiveData variable in your ViewModel, set it to the returned Live Data from Repository.
In the Fragment observe to the LiveData variable of your ViewModel not the one returned from Repository.
That way, your observe method will get triggered on very first time and only when value of your data from repository changes.

Why is the value param nullable in Observer from Android Architecture Components?

Fixed in androix.lifecycle 2.0.0-beta01.

Please report android Team if you encounter any issues.



Related Topics



Leave a reply



Submit