how to shared viewmodel in NavGraphBuilder.navigation between dialog and composable?
my code
navigation(startDestination = Stage.First.name, route = "main") {
dialog(Stage.First.name){
it.provideViewModel<MyViewModel> { vm ->
MyDialog(vm)
}
}
composable(Stage.Second.name) {
it.provideViewModel<MyViewModel> { vm ->
Second(vm)
}
}
composable(Stage.Third.name) {
it.provideViewModel<MyViewModel> { vm ->
Third(vm)
}
}
}
@Composable
inline fun <reified T : ViewModel> NavBackStackEntry.provideViewModel(
content: @Composable (T) -> Unit
) {
val parentId = destination.parent!!.id
val parentEntry = remember(this) { navCon.getBackStackEntry(parentId) }
val viewModel = hiltViewModel<T>(parentEntry)
"vmHashcode".log("${destination.route} : ${viewModel.hashCode()}")
content(viewModel)
}
This code is shared between composable and composable. But,it cannot be shared in composable and dialog.
Any solution?
ViewModel. I believe there is nothing wrong in your code. When you create an instance ofMyViewModelit's always use the sameViewModelOwner, which was your NavGraph. Keep in mind that your code will always return the same instance ofViewModelwhen your destination is still in the same scope of the NavHost