I was just exploring on Compose navigation. So, we...
# compose
a
I was just exploring on Compose navigation. So, we have the following for scoping ViewModel to the destination.
Copy code
val exampleViewModel = hiltNavGraphViewModel<ExampleViewModel>()
However, I couldn’t find anything or any info on passing a
ViewModelProvider.Factory
above (in case there are parameters for the ViewModel constructor). Am I missing something or is it yet to be developed?
l
You should check @HiltViewModel annotation and Hilt/navigation documentation for Compose here
a
So the key is to use
viewModel()
instead right?
g
@Arun this isn't using any di, but might help:
Copy code
composable(
            "${Screen.PlayerScreen.route}/{id}",
            arguments = listOf(navArgument("id") { type = NavType.IntType })
        ) {
            val arguments = requireNotNull(it.arguments)
            val playersViewModel = viewModel<PlayersViewModel>(
                factory = PlayersViewModelFactory(
                    it,
                    PlayersRepository(),
                    arguments
                )
            )
            PlayersScreen(playersViewModel)
        }
a
Thanks @Gabriel. One question however, doesn’t Hilt get the dependencies when simply using
viewModel()
. My ViewModel has few dependencies in its constructor that Hilt is supposed to provide. Using
hiltNavGraphViewModel
inside
composable
destination just works out of the box. However, if I use simply
viewModel()
, it throws Runtime exception that it can’t create an instance of the ViewModel.
The docs however states that it should fulfil all the dependencies while using
viewModel()
. 🤔
l
Are you using hilt-navigation-compose artifact ?
i
If you are using a HiltViewModel, you must use their factory. That's what
hiltNavGraphViewModel()
does - automatically uses the right factory for you. If you're not using Hilt, then use
viewModel()
and pass it your custom factory, which it takes as an optional parameter
👍 1
a
Thanks for the help. Will explore more around it.
a
@/Ian Lake Does the documentation need updating?
The 
viewModel()
 function mentioned in the ViewModel section automatically uses the ViewModel that Hilt constructs with the 
@HiltViewModel
 annotation. We’ve provided documentation with information about Hilt's ViewModel integration.
https://developer.android.com/jetpack/compose/libraries#hilt
ah, we need to use it if we’re using compose navigation
If your 
@HiltViewModel
 annotated 
ViewModel
 is scoped to the navigation graph, use the 
hiltNavGraphViewModel
 composable function that works with fragments or activities that are annotated with 
@AndroidEntryPoint
.
i
Yup, that's why there are two sections