My ViewModel:
class MyVM(
app: Application,
private val observableImpl: BaseObservable,
/* other colaborators*/
) : AndroidViewModel(app), Observable by observableImpl {
var currencyCode: String by Delegates.observable("") { _, _, newValue ->
/* business logic methods */
notifyPropertyChanged(BR.currencyCode)
}
@Bindable get
}
My layout:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="vm"
type="path.to.MyVM" />
</data>
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{vm.currencyCode}"
app:layout_constraintEnd_toEndOf="parent" />
</android.support.constraint.ConstraintLayout>
</layout>
When currencyCode
gets updated in the data model, TextView
does not change the text automatically.
I have tried to get rid of inheriting from AndroidViewModel
and defined MyVM
as follows:
class MyVM(/* other colaborators*/) : BaseObservable() {
}
And it worked. The problem is that I cannot throw away the inheritance from AndroidViewModel
in my production code.
There is a workaround though:
val currencyCode = ObservableField<String>()
But I am not comfortable with using ObservableFields in my ViewModel. Do you have any suggestions?