在collectasstate中获取旧响应

问题描述 投票:0回答:1
var authViewModel: UserAuthViewModel = hiltViewModel()
val userData by authViewModel.authUserData.collectAsState()

我点击一下即可调用api

} else {
if (textUser.contains("@")) { // for email
sharedViewModel.addType(false)
sharedViewModel.addUsername(textUser)
navigation = true
authViewModel.getAuthUserDataEmail(textUser = textUser)
loading = true
userData
} else {

在底部我会像这样处理响应

LaunchedEffect(userData,navigation) {
    if (userData != null && navigation) {
        when (userData?.result?.user_exist) {
            "USER_NOT_EXISTS" -> {
                navController.navigate(NavScreens.REGISTRATION.route)
            }
            "ACCOUNT_EXISTS" -> {
                navController.navigate(NavScreens.LOGIN.route)
            }
            "ACCOUNT_NOT_VERIFIED" -> {
                sharedViewModel.addOtpType("account_verification")
                navController.navigate(NavScreens.VERIFY_ACCOUNT.route)
            }
            else -> {
                Toast.makeText(context, "${userData?.message}", Toast.LENGTH_SHORT).show()
            }
        }
        loading = false
        navigation = false
    }
}

这是我的视图模型:

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 {
            var result = repository.getAuthUserData(AuthUser(username = textUser))
            Log.d("TAG", "getAuthUserDataEmail: ${authUserData.value?.result?.user_exist}")
        }
    }

问题是,假设我输入了一个注册用户,所以条件 1 为真,我进入登录屏幕。现在假设我回来并输入一个未注册的用户,所以应该进入注册屏幕,但我进入了登录屏幕。

现在这是一个条件问题,当我再次点击 api 时,它会转到注册屏幕,表明我收到一个旧响应,这导致它给出不需要的结果。

我该如何解决这个问题?

android kotlin retrofit viewmodel jetpack
1个回答
0
投票

所以我通过在再次访问 api 之前清除响应来解决这个问题

> fun clearAuthUserData() {
>         _authUser.value = null
>     }

并像这样在视图模型中调用它

fun getAuthUserDataEmail(textUser: String) {
    viewModelScope.launch {
        repository.clearAuthUserData()
        var result = repository.getAuthUserData(AuthUser(username = textUser))
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.