Keep Your LiveData Safe when navigating back.

Taku Semba
2 min readJan 30, 2019

LiveData + Navigation

LivaData helps you observe data. Navigation helps you manage transitions. However, when you use both there is something you have to pay extra attention to.

Let’s think of a situation where you develop a single-activity app with two fragments in it. (MainActivity, Fragment1, Fragment2.)

I had a code like this below. Observing LiveData on onViewCreated, and have a click listener to navigate to Fragment2.

Assume a user started an app and transited from Fragment1 to Fragment2, then popped back to Fragment1 using findNavController().navigateUp().

What happened to me is that when the user popped back to the Fragment1, onViewCreated() is called on Fragment1 and started observing LiveData again even though there is one more observer that had been already added when the user started the app.

In short, there are two active observers at the same time.

This is because the observers that had been added will be removed when Fragment1 is in the Lifecycle.State.DESTROYED state, but the Fragment1 has not been in the DESTROYED state yet.

Solution

To solve this problem, I found a class called viewLifecycleOwner. ViewLifecycleOwner has its own lifecycle associated with a view, and it will be in the Lifecycle.Event.ON_DESTROY state when the Fragment’s onDestroyView() called, not onDestroy().

The code will be something like this below.

--

--