Nat Strangerweather
02/11/2023, 12:21 PMNat Strangerweather
02/11/2023, 12:22 PMprivate val mainViewModel: MainViewModel by viewModels()
and in my Composable like this:
val mainViewModel: MainViewModel = viewModel()
This works as long as I do not put my Composable in the Navigation Graph. I assume a new instance of my viewModel is created in the Navigation process. I would need to keep the same instance of my MainActivity viewModel in my Composable.Zaki Shaikh
02/11/2023, 12:45 PMNat Strangerweather
02/11/2023, 1:50 PMZaki Shaikh
02/11/2023, 1:50 PMNat Strangerweather
02/11/2023, 1:55 PM@Composable
fun Navigation() {
val navController = rememberNavController()
NavHost(
navController = navController,
startDestination = Routes.VERIFY_REMOTE_SCREEN
) {
composable(Routes.VERIFY_REMOTE_SCREEN) {
VerifyRemoteApp(
onNavigate = {
navController.navigate(it.route)
}
)
}
composable(Routes.ADDRESS_LIST) {
AddressListScreen(
onNavigate = {
navController.navigate(it.route)
}
)
}
composable(
route = Routes.ADD_EDIT_ADDRESS + "?addressId={addressId}",
arguments = listOf(
navArgument(name = "addressId") {
type = NavType.IntType
defaultValue = -1
}
)
) {
AddEditAddressScreen(onPopBackStack = {
navController.popBackStack()
}
)
}
}
}
And I get to it with this:
setContent {
MaterialTheme {
Navigation()
}
}
This is in my MainActivity. Basically I need to pass the viewModel from MainActivity to VerifyRemoteApp
.Zaki Shaikh
02/11/2023, 1:59 PMfun Navigation(viewModel: MainViewModel) {
//your nav host code
}
Zaki Shaikh
02/11/2023, 2:00 PMsetContent {
MaterialTheme {
Navigation(mainViewModel)
}
}
Zaki Shaikh
02/11/2023, 2:01 PMNat Strangerweather
02/11/2023, 2:01 PMMini
02/12/2023, 5:36 AMviewModel()
You should be able to pass the activity as the ViewModelStoreOwner to the viewModel()
function instead to get the behaviour you want, something along the lines of
= viewModel(
viewModelStoreOwner = context.getActivity() as ViewModelStoreOwner
)
Zaki Shaikh
03/03/2023, 5:17 AMval mainViewModel = LocalViewModelStoreOwner.current?.let {
viewModel<MainViewModel>(viewModelStoreOwner = it)
}