Why LiveData observer is being triggered twice for a newly attached observer

I have introduced just one change in your code:

noteViewModel = ViewModelProviders.of(this).get(NoteViewModel.class);

instead of:

noteViewModel = ViewModelProviders.of(getActivity()).get(NoteViewModel.class);

in Fragment‘s onCreate(Bundle) methods. And now it works seamlessly.

In your version you obtained a reference of NoteViewModel common to both Fragments (from Activity). ViewModel had Observer registered in previous Fragment, I think. Therefore LiveData kept reference to both Observer‘s (in MainFragment and TrashFragment) and called both values.

So I guess the conclusion might be, that you should obtain ViewModel from ViewModelProviders from:

  • Fragment in Fragment
  • Activity in Activity

Btw.

noteViewModel.getTrashedNotesLiveData().removeObservers(this);

is not necessary in Fragments, however I would advise putting it in onStop.

Leave a Comment