Keep Your LiveData Safe when navigating back.

Taku Semba
Jan 30, 2019 · 2 min read

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.


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.

Taku Semba

Written by

Android Engineer at AbemaTV Github:

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade