https://kotlinlang.org logo
#compose
Title
# compose
d

dagomni

11/03/2020, 11:28 AM
NavBackStackEntry in composable() returns a different ViewModelStore every time it's called. Is it a desired behavior?
i

Ian Lake

11/03/2020, 2:44 PM
Each destination instance has its own Lifecycle, ViewModelStore, SavedStateRegistry, and remembered state, yes. If you hit the system back button to go back to an existing destination instance, you'll get the same ones as the first time. That's how state restoration works
d

dagomni

11/03/2020, 2:53 PM
I'm not talking about different destinations. The same destination returns different ViewModelStore every time it's launched (BottomNavigation, using the example from the docs)
Copy code
navController.popBackStack(navController.graph.startDestination, false)

if (currentRoute != routeToOpen) {
    navController.navigateTo(routeToOpen)
}
So going from first tab to the second tab and then the first one again gives different ViewModelStore objects for the first destination
i

Ian Lake

11/03/2020, 2:56 PM
Whenever you
navigate
, you are creating a brand new instance. The only time in the current world where you get a previously created instance is when you hit the system back button
One of the upcoming features of Navigation (which Navigation Compose will get as well) is multiple back stacks - the saving and restoring of separate back stacks and all of the state and destination instances associated with that back stack.
That will give you the behavior you're looking for where the state of each bottom nav item is saved and restored
d

dagomni

11/03/2020, 3:11 PM
Ah that makes sense. Thanks for clarification
6 Views