我有一个LiveData属性,用于这样的登录表单状态
private val _authFormState = MutableLiveData<AuthFormState>(AuthFormState())
val authFormState: LiveData<AuthFormState>
get() =_authFormState
AuthFormState数据类的每个字段都有子数据对象
data class AuthFormState (
var email: FieldState = FieldState(),
var password: FieldState = FieldState()
)
并且FieldState类看起来像这样
data class FieldState(
var error: Int? = null,
var isValid: Boolean = false
)
当用户在字段中输入一些值时,相应的FieldState对象将被更新并分配给父AuthFormState对象
fun validateEmail(text: String) {
_authFormState.value!!.email = //validation result
}
问题是在这种情况下未通知authFormState观察器。
是否可以通过程序触发通知?
fun validateEmail(text: String) {
val new = _authFormState.value!!
new.email = //validation result
_authFormState.setValue(new)
}
_authFormState.value = _authFormState.value
触发刷新。您可以编写一个扩展方法来使它更干净:fun <T> MutableLiveData<T>.notifyValueModified() {
value = value
}
对于这样一个简单的数据类,我建议使用不变性以避免此类问题(将所有这些var
替换为val
)。用以下内容替换validateEmail()
:
fun AuthFormState.withValidatedEmail() = AuthFormState( validate(email), // whatever you need to do here password )
然后在修改时将实时数据值手动更改为新值。