[英]StateFlow don't emit when the new value same last value
I have a login form.我有一个登录表单。 I use StateFlow
to send LoginResult
(after call API) from ViewModel
to Activity
.我使用StateFlow
将LoginResult
(调用 API 后)从ViewModel
发送到Activity
。 In the Activity, I will show an error dialog if login failed.在活动中,如果登录失败,我将显示一个错误对话框。
It works well for the first time but from the second time I login failed, the error dialog won't show again.它第一次运行良好,但从我第二次登录失败后,错误对话框将不再显示。 I tested both .value
and .emit
on StateFlow
我在StateFlow
上测试了.value
和.emit
private val _loginResult = MutableStateFlow(LoginResult())
val loginResult: StateFlow<LoginResult> = _loginResult
fun login(email: String, password: String) {
viewModelScope.launch {
when (val result = loginRepository.login(email, password)) {
is Result.Fail-> {
_loginResult.value = LoginResult(error = "Login failed")
// _loginResult.emit(LoginResult(error = "Login failed")) same issue
}
...
}
}
}
For this case, I use SharedFlow
so my Activity
still able to collect the new value even it same the last value对于这种情况,我使用SharedFlow
所以我的Activity
仍然能够收集新值,即使它与最后一个值相同
private val _loginResult = MutableSharedFlow<LoginResult>()
val loginResult: SharedFlow<LoginResult> = _loginResult
...
_loginResult.emit(LoginResult(error = "Login failed"))
Another possible solution but it's not good is change my current data class LoginResult(...)
to class LoginResult
.另一种可能的解决方案,但它不好是将我当前的data class LoginResult(...)
更改为class LoginResult
。 Then every new instance of LoginResult
will different然后每个新的LoginResult
实例都会不同
That's by default.这是默认设置。 What you could do is to emit one value when the login is in progress, before emitting the result.您可以做的是在登录过程中发出一个值,然后发出结果。 That way you would have a sequence like:这样你就会有一个像这样的序列:
in_progress -> error -> in_progress -> error
Apps usually display a spinner or something when the in_progress
or loading
or whatever is emitted.应用程序通常会在in_progress
或loading
或其他任何东西发出时显示微调器或其他东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.