Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent ViewModel from getting killed when navigating in Android using Kotlin?

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?

like image 329
Harry Avatar asked Oct 20 '25 12:10

Harry


1 Answers

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:

  1. Before: [A -> B -> C]
  2. The popUpTo happens first, leaving you with [A]
  3. Then the 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.

like image 174
ianhanniballake Avatar answered Oct 23 '25 02:10

ianhanniballake



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!