Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Navigation component graph stop working properly when I use navController in LiveData observer

I'm using android navigation component in my demo app. I have a pretty straightforward case. One activity, two fragments, A and B. I have set up navigation controls as in the example app from Google. And when I'm tryin to open fragment B from A using simple onClickListener, like this:

val button.setOnClickListener {
       val action = AFragmentDirections.openFragmentB()
       findNavController().navigate(action)
    }

Everything works fine. The B fragment opens, and by taping on back button it pops up. But when I'm trying to use it from LiveData observer, like this:

viewModel.openFragmentB.observe(viewLifecycleOwner, Observer {
        val action = AFragmentDirections.openFragmentB()
        findNavController().navigate(action)
    })

Fragment B opens, but by taping on back button app crashes with the error navigation destination com.myapp:id/open_fragmetn_b is unknown to this NavController.

Why is this happening and how to use navigation component with LiveData?

like image 988
Alexandr Sushkov Avatar asked Dec 01 '18 23:12

Alexandr Sushkov


1 Answers

This crash occur because when you click on back button, your viewmodel openFragmentB observer is notified again, and it is trying to navigate to Fragment B using action openFragmentB, but at this point NavController current destination is still Fragment B, and Fragment B don't have action openFragmentB.

There is multiple solutions for this, the simple one is to add inside your observer check if the value is not null and at the end set openFragmentB value to null:

if(it!=null) {
    val action = AFragmentDirections.openFragmentB()
    findNavController().navigate(action)
    viewModel.openFragmentB.value=null
}

But for better approach you can read about SingleLIveEvent: https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150

like image 85
Alex Avatar answered Nov 09 '22 00:11

Alex