gts13
12/21/2022, 10:19 AMclass MainActivity : FragmentActivity() { // I use the FragmentActivity because of biometrics
private val viewModel: MainViewModel by viewModels()
MyAppTheme {
val state by viewModel.state.collectAsStateWithLifecycle()
val incomingEvent = viewModel.incomingEvent
MyApp(
isUserRegistered = state.isUserRegistered,
hasUserProfile = state.hasUserProfile,
incomingEvent = incomingEvent
)
}
}
@Composable
fun MyApp(
isUserRegistered: Boolean,
hasUserProfile: Boolean,
incomingEvent = incomingEvent
) {
val navController = rememberAnimatedNavController()
if (isUserRegistered) {
NavigationHost(
Screen.OnboardingDestination.route,
navController
)
} else {
NavigationHost(
Screen.MainBashboard.route,
navController
)
}
when (incomingEvent) {
is profileEvent -> {
navController.navigateToProfileScreen(incomingEvent.getSomeArgs)
}
is settingsEvent -> {
navController.navigateToSettingsScreen(incomingEvent.getSomeArgs)
}
...
}
}
Now I need to access the MainViewModel
from other composable screens that are in the NavigationHost.
The reason is that I need to show a specific screen based on an incoming event that I collect from a flow in the MainViewModel
. The MainVIewModel
holds some data in memory that I need to access them only from other composables.Filip Wiesner
12/21/2022, 10:22 AMNow I need to access theWhat exactly do you need it for? State can be passed down and events can be passed up using callbacks. There shouldn't be a need for the VM referencefrom other composable screens that are in the NavigationHostMainViewModel
gts13
12/21/2022, 12:22 PM