Observe LiveData from ViewModel in Fragment

Sagar Begale
4 min readApr 17, 2019

Google introduced Android architecture components which are basically a collection of libraries that facilitate robust design, testable, and maintainable apps. It includes convenient and less error-prone handling of LifeCycle and prevents memory leaks.

Although these components are easy to use with exhaustive documentation, using them inappropriately leads to several issues which could be difficult to debug.

Problem

One such issue our team came across was observing LiveData from ViewModel in Fragment. Let's say we have two Fragments: FragmentA (which is currently loaded) & FragmentB which user can navigate to. FragmentA is observing data from ViewModel via LiveData.

When

  • The user navigates to FragmentB, FragmentA gets replaced by FragmentB and the transaction is added to backstack.
  • After some actions on FragmentB user presses the back button and returns to FragmentA

Then

  • LiveData observer in FragmentA triggered twice for single emit.

Following is the code Snippet:

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final TestViewModel viewModel =…

--

--

Sagar Begale
Sagar Begale

Responses (9)