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 = ViewModelProviders.of(getActivity()).get(TestViewModel.class);
viewModel.getTestEntity().observe(this, testEntity -> {
//Do something
});
}

If the user navigates to FragmentB again and presses back to visit FragmetnA, the LiveData observer was triggered thrice and it continued to increase

Debugging Approach

The initial thought was somehow(due to Fragment going though lifecycle) ViewModel was triggering LiveData multiple data on the same Observer. We added the following log to ensure this is the case:

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final ProductListViewModel viewModel =
ViewModelProviders.of(getActivity()).get(ProductListViewModel.class);
viewModel.getProducts().observe(this, new Observer<List<ProductEntity>>() {…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Sagar Begale

Mobile lead Engineer at Getgo

Recommended from Medium

Lists

See more recommendations