so my question is pretty straight forward. viewmodel needs a scope to stay alive. such as activity or fragment. so I guess there must be a class associated with the navgraph
that survives through multiple fragments.so how is that implemented?
val viewModel by navGraphViewModels(R.id.my_nav_graph).
As per the Reference a destination using NavBackStackEntry documentation:
Starting with Navigation 2.2.0, you can get a reference to the
NavBackStackEntry
for any destination on the navigation stack by callingNavController.getBackStackEntry()
, passing it a destination ID.
The returned
NavBackStackEntry
provides aLifecycle
,a ViewModelStore
, and a SavedStateRegistry at the destination level. These objects are valid for the lifetime of the destination on the back stack. When the associated destination is popped off the back stack, the Lifecycle is destroyed, the state is no longer saved, and any ViewModel objects are cleared.
So when you call by navGraphViewModels()
, it is the NavBackStackEntry
for that navigation graph that is used. As that NavBackStackEntry
remains on the back stack while you're on any of the destination within that graph, that same NavBackStackEntry
is returned no matter what destination in that graph you call by navGraphViewModel()
on, ensuring that those multiple fragments all have a shared scope. Once you pop all of the fragments off the back stack, the navigation graph and its NavBackStackEntry
are also popped, clearing out that shared state.