My `hiltViewModel` calls (from the `androidx.hilt....
# compose
s
My
hiltViewModel
calls (from the
androidx.hilt.naviagtion.compose
lib) returns a new instance of the retrieved viewmodel as opposed to returning the same viewmodel scoped to a navigation graph where it is first retrieved. Any ideas what I might be missing?
c
Got any code to show? I believe that it should give you back the same instance if that instance is still around, else it will create a new one.
s
Thanks @Colton Idle, I am not doing anything special:
Copy code
@HiltViewModel
class MyViewModel @Inject constructor() : ViewModel

...
navigation(route = "root", startDestination="...") {
  // Expected: MyViewModel should be the same instance in the composables below
  // Actual: MyViewModel is different instances in the comoosables
  composable(...) {
     hiltViewModel<MyViewModel>
  }

  composable(...) {
     hiltViewModel<MyViewModel>
  }
}
...
a
@Smorg Try it like this
Copy code
composable(route) {
                val viewmodel = hiltViewModel<ViewModel>(                  navController.getBackStackEntry(navigationRoute)
)
                Composable(viewmodel ,
                    navigateUp = { 
navController.navigateUp() 
}
                )
            }
s
Thanks @Anthony. I just read the release notes and found the same.
👍 1
a
You need to pass into the viewmodel the route it is scoped to, which would be the navigation route "root" in this case.
👍 1