简体   繁体   中英

Navigate by checking login state with jetpack compose (Conditional Nested Nav graphs)

I am trying to implement a way to check authentication status from the room database before and navigate (Conditional navigation)

The requirement is as follows

在此处输入图像描述

I have a session manager with the following code

    private val _sessionState = MutableStateFlow(SessionState.Loading)
    val sessionState: StateFlow<SessionState> = _sessionState

    init {
        coroutineScope.launch {
            sessionRepo.getActiveSession()
                .collect { resource ->
                    _sessionState.value = when (resource) {
                        is Resource.Success -> {
                            if (resource.data == null) {
                                SessionState.InActive
                            } else {
                                SessionState.Active
                            }
                        }
                        else -> throw IllegalStateException("Failed to load session")
                    }
                }
        }
    }

How can I check this with jetpack compose

If i understand your question correctly I would do it this way:

@Composable
fun App(mainViewModel: MainViewModel) {
    val navController = rememberNavController()

    LaunchedEffect(Unit) {
        mainViewModel.checkAuth(navController)
    }
    
    NavHost(
        navController = navController,
        startDestination = RootNavigation.Home.route
    ) {
        
        composable(RootNavigation.Home.route) {
            SplashScreen()
        }

        loginGraph(navController)

        workspaceGraph(navController)
    }
}

At MainViewModel:

fun checkAuth(navController: NavHostController) {
    viewModelScope.launch {
        ...//your code
        
        if (resource.data == null)                            
            navController.navigateAndReplaceStartRoute(RootNavigation.Login.route)
        else navController.navigateAndReplaceStartRoute(RootNavigation.Workspace.route)

        ...//your code
    }
}

Did I answer your question?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM