https://kotlinlang.org logo
#compose
Title
# compose
a

Archie

02/27/2021, 9:55 AM
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

jaqxues

02/27/2021, 10:15 AM
There is this entire GitHub issue about Hilt and scoping viewmodels to composables
a

Archie

02/27/2021, 10:17 AM
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

jaqxues

02/27/2021, 10:19 AM
Yes, should be