使用 MediatorLiveData 将多个 LiveData 值合并为一个

Combine multiple LiveData values into one using MediatorLiveData

我有一个电子邮件、密码和 phone 号码,这些都是用户键入时片段实时更新的所有实时数据值。

我怎样才能拥有一个观察所有这三个变量的实时数据变量,以及returns基于它们所有组合结果的东西?

ViewModel

class AuthenticationViewModel: ViewModel() {
    var email: MutableLiveData<String> = MutableLiveData("")
    var password: MutableLiveData<String> = MutableLiveData("")
    var phoneNumber: MutableLiveData<Int> = MutableLiveData(0)

    val isFormValid: MediatorLiveData<Boolean> = {
        // if email is valid
        // and if password is valid
        // and if phoneNumber is valid
        // return true
        // How do I do this?
    }
}

片段

binding.emailInput.addTextChangedListener { email ->
    viewModel.email.value = email.toString()
}

viewModel.isFormValid.observe(this, {
    // do what I want in real time
})

尝试像这样将每个 liveData 添加为源,并在其中一个触发更改时检查另一个 liveData 的值: ViewModel

class AuthenticationViewModel: ViewModel() {
    val email: MutableLiveData<String> = MutableLiveData("")
    val password: MutableLiveData<String> = MutableLiveData("")
    val phoneNumber: MutableLiveData<Int> = MutableLiveData(0)

    val isFormValid: MediatorLiveData<Boolean> = MediatorLiveData().apply {
        addSource(email) { emailValue -> isValidEmail(emailValue) && isValidPassword(password.value) && isValidPhoneNumber(phoneNumber.value) }
        addSource(password) { passwordValue -> isValidEmail(email.value) && isValidPassword(passwordValue) && isValidPhoneNumber(phoneNumber.value) }
        addSource(phoneNumber) { phoneNumberValue -> isValidEmail(email.value) && isValidPassword(password.value) && isValidPhoneNumber(phoneNumberValue) }
    
    }
}

然后像往常一样观察实时数据:

片段

binding.emailInput.addTextChangedListener { email ->
    viewModel.email.value = email.toString()
}

viewModel.isFormValid.observe(this, {
    // do what I want in real time
})

https://medium.com/codex/how-to-use-mediatorlivedata-with-multiple-livedata-types-a40e1a59e8cf 启发的解决方案,有点相同但不使用 Triple 和新的 class,您也可以添加任意数量。