share hiltviewmodel in multiple nested navigation

27 Views Asked by At

I'm new to coding in compose, basically I want to share the my auth view model to both 'auth' and 'dashboard' nested navigation routes. I've seen some examples on how to share between composables inside NavHost but not navigations (nested graph), need it to handle auth data and functions. any help would be grateful.

also is my auto-navigation method used to navigated if logged in/out is good practice?

val authViewModel = hiltViewModel<AuthViewModel>()
val navController = rememberNavController()
var isComingBackFromDifferentScreen by remember { mutableStateOf(false) }


NavHost(
  navController = navController,
  startDestination = "auth"
) {

  // AUTH
  navigation(
    startDestination = Screens.Login(),
    route = "auth"
  ) {
    composable(Screens.Login()) {
      val authState = authViewModel.authState.collectAsStateWithLifecycle().value
      LaunchedEffect(key1 = authState.isLoggedIn) {
        if (authState.xcAuthResponse != null) {
          navController.navigate(Screens.Dashboard()) {
            popUpTo(navController.graph.startDestinationId)
              { inclusive = true }
          }
        }
      }
      LoginScreen(
        authViewModel = authViewModel, navController = navController
      )
    }

    composable(Screens.AddProfile()) {
      AddProfileScreen(
        authViewModel = authViewModel, navController = navController
      )
    }
  } 
  
  // DASHBOARD
  navigation(
    startDestination = Screens.Dashboard(),
    route = "dashboard"
  ) {
    composable(Screens.Dashboard()) {
      val authState= authViewModel.authState.collectAsState().value

      if (!authState.isLoggedIn) {
        navController.navigate(Screens.Login()) {
          popUpTo(navController.graph.startDestinationId)
            { inclusive = true }
        }
      }

      DashboardScreen(
        onBackPressed = onBackPressedDispatcher::onBackPressed,
        isComingBackFromDifferentScreen = isComingBackFromDifferentScreen,
        resetIsComingBackFromDifferentScreen = {
          isComingBackFromDifferentScreen = false
        }
      )
    }
  }
}
                
0

There are 0 best solutions below