Consider this example.
For authentication, we'll be using 2 screens - one screen to enter phone number and the other to enter OTP.
Both these screens were made in Jetpack Compose and the for the NavGraph, we are using compose navigation.
Also I have to mention that DI is being handled by Koin.
val navController = rememberNavController()
NavHost(navController) {
navigation(
startDestination = "phone_number_screen",
route = "auth"
) {
composable(route = "phone_number_screen") {
// Get's a new instance of AuthViewModel
PhoneNumberScreen(viewModel = getViewModel<AuthViewModel>())
}
composable(route = "otp_screen") {
// Get's a new instance of AuthViewModel
OTPScreen(viewModel = getViewModel<AuthViewModel>())
}
}
}
So how can we share the same viewmodel among two or more composables in a Jetpack compose NavGraph?