The observable in the question is ObservableFields
, not RxJava Obervervable
like the other answers mentioned.
It's a good question to compare between LiveData
and ObservableFields
. Because live data is lifecycle aware, it can do a lot of things. You can observe the live data from the view model and update the UI from the code. You can also extend the live data and use it like an event bus to notify the data change between 2 Android components and you don't need to worry about the lifecycle issue.
But does that mean it is not necessary to use ObservableFields
at all? No. Because data binding itself is lifecycle aware, it already checks when the view is active. You can use LiveData
or ObservableFields
or even Stateflow
In one-way data binding, you can use any of them, but in 2-way data binding, I still prefer observable fields, because it's more flexible, and you can easily write custom logic in the observable field setter, and when the UI changes, it can call the setter to do some additional stuff.
class LoginViewModel : BaseObservable {
// val data = ...
@Bindable
fun getRememberMe(): Boolean {
return data.rememberMe
}
fun setRememberMe(value: Boolean) {
// Avoids infinite loops.
if (data.rememberMe != value) {
data.rememberMe = value
// React to the change.
saveData()
// Notify observers of a new value.
notifyPropertyChanged(BR.remember_me)
}
}
}
And in xml file.
<CheckBox
android:id="@+id/rememberMeCheckBox"
android:checked="@={viewmodel.rememberMe}"
/>