Hi, just would like to share and confirm. This is ...
# compose
a
Hi, just would like to share and confirm. This is how I scope my
ViewModel
to a
NavGraph
.
Copy code
@Composable
inline fun <reified VM : ViewModel> navGraphViewModel(
    route: String,
    navController: NavController,
): VM {
    // Now get the NavBackStackEntry associated with the parent
    val backStackEntry = navController.getBackStackEntry(route)

    val context = LocalContext.current
  
    return ViewModelLazy(
        viewModelClass = VM::class,
        storeProducer = { backStackEntry.viewModelStore },
        factoryProducer = { HiltViewModelFactory(context, backStackEntry) }
    ).value
}
Was wondering how others are doing theres? (I am using Hilt for my project, the ViewModelFactory could be passed in if you are not using Hilt)
Its a slightly modified version of ian lake's answer here: https://stackoverflow.com/questions/64955859/scoping-states-in-jetpack-compose I was wondering if there is a actually api for this.
j
There is this entire GitHub issue about Hilt and scoping viewmodels to composables
a
I believe that was fixed with the recent releases? isn't it? Doesn't
Copy code
viewModel(factory = HiltViewModelFactory(LocalContext.current, it))
fixes the issue atleast temporarily?
j
Yes, should be