Hilt with Jetpack Compose Navigation
Asked Answered
K

1

8

I checked this info https://developer.android.com/jetpack/compose/libraries#hilt-navigation how to inject ViewModel to a compose screen.

For now I implemeted like this for my test app:

NavHost(
    navController = navController,
    startDestination = startDestination,
    modifier = modifier
) {
    composable(Screen.Topics.name) {
        val parentEntry = remember { navController.getBackStackEntry(Screen.Topics.name) }
        val topicsViewModel = hiltViewModel<TopicsViewModel>(parentEntry)
        TopicsScreen(
            topicsViewModel = topicsViewModel,
            openDrawer = openDrawer,
            navigateToTopicDetails = { topic -> actions.navigateToTopicsDetails(topic) }
        )
    }
    ...

Is there will be any difference if I use

val parentEntry = remember { navController.getBackStackEntry(Screen.Topics.name) }
val topicsViewModel = hiltViewModel<TopicsViewModel>(parentEntry)

or just

val topicsViewModel = hiltViewModel<TopicsViewModel>()

I guess first one is needed only if we use nested graphs and we want to get ViewModel for specific graph scope https://developer.android.com/jetpack/compose/navigation#nested-nav

So in my case the scope is the same for both methods if I don't use nested graphs?

So can I just use hiltViewModel<TopicsViewModel>() in my case?

Kolinsky answered 24/3, 2022 at 13:10 Comment(0)
J
1

I think you have already provided a clear explanation for your question, but to sum it up, hiltViewModel<TopicsViewModel>(parentEntry) is used when you have nested navigation graphs. When you use hiltViewModel with parentEntry, you are telling Compose to create a ViewModel instance that is scoped to the nested graph.

Since you are not using nested graphs in your code, you can use the simpler version of hiltViewModel without parentEntry. This will create a ViewModel instance that is scoped to the current screen's navigation graph, which is what you want.

Judgemade answered 4/4, 2023 at 21:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.