Consider this:
We have: MainActivity, FragmentA, FragmentAViewModel, FragmentB, FragmentC
MainActivity is being displayed and we are on FragmentA by default. Click a button and navigate to FragmentB. Click a button and navigate to FragmentC. Now on FragmentC we want to click a button to navigate to FragmentA, but we don't want to have multiple copies of FragmentA in the backstack. So, we want to popup backstack until we reach FragmentA. This is how I do it:
findNavController().navigate(R.id.nav_FragmentA, null, navOptions {
popUpTo(R.id.nav_FragmentA)
launchSingleTop = true
})
This works as expected, however FragmentAViewModel dies in the process, and when you reach FragmentA, all of the data stored in FragmentAViewModel is lost.
Is there any way to navigate in the manner mentioned above, without having FragmentAViewModel destroyed?
If you want to go back to a Fragment that is already on the back stack, you'll want to use navController.popBackStack()
:
navController.popBackStack(R.id.nav_FragmentA, false)
The important thing to realize about navigate
is that it will always create a new Fragment instance. So what is actually happening is:
A
-> B
-> C
]popUpTo
happens first, leaving you with [A
]navigate
with launchSingleTop
happens, creating a new instance of Fragment A, A'
. Navigation detects that A
and A'
are the same destination, so launchSingleTop
replaces A
with A'
, leaving you with [A'
].This differs from popBackStack
, which simply takes you back to [A
], which is what you wanted all along.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With