var authViewModel: UserAuthViewModel = hiltViewModel()
val userData by authViewModel.authUserData.collectAsState()
fun checkUserforEmnail(
sharedViewModel: SharedViewModel,
userData: AuthResponseModel?,
authViewModel : UserAuthViewModel,
navController: NavController,
textUser: String
) {
Log.d("TAG", "checkUserforEmnail: ${userData}")
if (userData == null){
authViewModel.getAuthUserDataEmail(textUser = textUser)
Log.d("TAG", "checkUserforEmnail: ${userData}")
}
if(userData?.result?.user_exist == "USER_NOT_EXISTS"){
navController.navigate(NavScreens.REGISTRATION.route)
}
else if(userData?.result?.user_exist == "ACCOUNT_EXISTS") {
sharedViewModel.addUsername(userName = textUser)
navController.navigate(NavScreens.LOGIN.route)
}
else if(userData?.result?.user_exist == "ACCOUNT_NOT_VERIFIED"){
}
}
ViewModel
@HiltViewModel
class UserAuthViewModel @Inject constructor(private val repository: Repository) : ViewModel() {
val authUserData: StateFlow<AuthResponseModel?> get() = repository.authUserData
fun getAuthUserData(textUser: String, countryCode:String){
viewModelScope.launch {
val result = repository.getAuthUserData(AuthUser(username = textUser, country_dial_code = countryCode))
}
}
fun getAuthUserDataEmail(textUser: String) {
viewModelScope.launch {
val result = repository.getAuthUserData(AuthUser(username = textUser))
}
}
}
所以问题是我在单击“okk”时称此为有趣,所以在第一次单击时我将用户数据记录为空,但是当我再次单击它时,它会按预期获取数据,所以我认为正在发生的事情是因为响应花费了一点时间,这是正常时间,我的代码不等待响应,因此默认响应为空并使用它,但第二次它使用 userData 中的新数据,我看到了响应。所以我的问题是如何解决这个问题
如果我正确理解您的数据流,您将请求发送到
getAuthUserDataEmail
,忽略返回值,而是从AuthResponseModel
收集repository.authUserData
。这是一种容易出错的方法。
不要使用
StateFlow
并在 Composable
中执行业务逻辑,而是使用 repository.getAuthUserData
返回的值并在 UserAuthViewModel
中的同一协程中更新 UI 状态。可组合项应基于该 UI 状态进行导航。
示例
ViewModel
:
sealed class AuthState {
object SignedOut : AuthState()
object Exist : AuthState()
object NotExist : AuthState()
object NotVerified : AuthState()
}
@HiltViewModel
class UserAuthViewModel @Inject constructor(private val repository: Repository) : ViewModel() {
private val _authState = MutableStateFlow<AuthState>(AuthState.SignedOut)
val authState: StateFlow<AuthState>
get() = _authState
fun getAuthUserDataEmail(textUser: String) {
viewModelScope.launch {
val userData = repository.getAuthUserData(AuthUser(username = textUser))
// update UI state here
if (userData?.result?.user_exist == "USER_NOT_EXISTS") {
_authState.value = AuthState.NotExist
}
// rest of the logic
}
}
}
可组合:
val authState by authViewModel.authState.collectAsStateWithLifecycle()
LaunchedEffect(authState) {
when (authState) {
AuthState.Exist -> { navController.navigate(NavScreens.LOGIN.route) }
AuthState.NotExist -> TODO()
AuthState.NotVerified -> TODO()
AuthState.SignedOut -> TODO()
}
}