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.