I'm using the Navigation component in my Jetpack Compose project and have a question about how argument values are accessed in SavedStateHandle of ViewModels.
When I define a route with arguments in my NavGraph and navigate to it, I can directly retrieve those argument values from the SavedStateHandle in the corresponding ViewModel, without explicitly setting them there myself.
Does the Navigation component internally store these argument values in the SavedStateHandle under their corresponding keys automatically? If so, could you please provide an explanation , insights or clarifications on this mechanism?
Here's a code snippet to illustrate setup(Reference : https://developersbreach.com/savedstatehandle-viewmodel-android/) :
// NavGraph composable
composable(
route = "detail_route/movieId",
arguments = listOf(
navArgument("movieId") {
type = NavType.IntType
}
)
) {
val viewModel = hiltViewModel<DetailViewModel>()
DetailScreen(
viewModel = viewModel
)
}
// DetailViewModel
class DetailViewModel(
savedStateHandle: SavedStateHandle
) : ViewModel() {
private val movieId: Int? = savedStateHandle["movieId"]
fun getMovieInformation() {
val movieData: Movie = repository.getSelectedMovieData(movieId)
}
}
Like Fragment stacks and Bundle arguments, NavController has features to manage navigation back stack NavBackStackEntry and its arguments.
When a movie list screen goes to a detail screen, NavHost(NavController) searches for a NavDestination and a movie detail back stack is pushed into NavHost with arguments from movie list NavArgumentType.
NavController in Compose functionality is so similiar with FragmentManager in fragment.