我有这些屏幕:
NavHost(
navController = navController,
startDestination = AuthScreen.route
) {
composable(
route = AuthScreen.route
) {
AuthScreen()
}
composable(
route = MainScreen.route
) {
MainScreen()
}
}
在MainActivity中,我需要根据身份验证状态将用户发送到右侧屏幕.因此,我使用:
val isUserSignedOut = viewModel.getAuthState().collectAsState().value
if (isUserSignedOut) {
navController.navigate(AuthScreen.route) {
popUpTo(navController.graph.id) {
inclusive = true
}
}
} else {
navController.navigate(MainScreen.route) {
popUpTo(navController.graph.id) {
inclusive = true
}
}
}
一切都按预期进行,因为我认为这是一个同步操作.现在,当用户通过身份验证时,我需要创建一个请求来判断用户类型.以下是我try 过的:
if (isUserSignedOut) {
navController.navigate(AuthScreen.route) {
popUpTo(navController.graph.id) {
inclusive = true
}
}
} else {
Request(
checkAdmin = { admin ->
if (admin) {
navController.navigate(AdminScreen.route) {
popUpTo(navController.graph.id) {
inclusive = true
}
}
} else {
navController.navigate(MainScreen.route) {
popUpTo(navController.graph.id) {
inclusive = true
}
}
}
}
)
}
这段代码的问题是,当我打开应用程序时,第一次显示的是AuthScreen
,即使用户已经通过了身份验证.换句话说,当我得到异步请求的响应时,显示的是AuthScreen
,我不希望这样.我需要go MainScreen
或AdminScreen
没有显示AuthScreen
第一.如何解决这个问题?
编辑:
@BenjyTec我从ViewModel获取auth状态:
fun getAuthState() = authRepo.getAuthState(viewModelScope)
以下是回购计划:
override fun getAuthState(viewModelScope: CoroutineScope) = callbackFlow {
val listener = FirebaseAuth.AuthStateListener { auth ->
trySend(auth.currentUser == null)
}
auth.addAuthStateListener(listener)
awaitClose {
auth.removeAuthStateListener(listener)
}
}.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(),
initialValue = auth.currentUser == null
)