Tips – clean code & less boilerplate
A few tips on how to keep the code clean and testable
1. Don’t want to have Android dependencies in viewModel, but still want it to handle clicks?
Create an onClick BindingAdapter that does not pass View, or use one from SecretSauce library.
2. Do you want to auto refresh your data in view by making viewModel Observable, but don’t like boilerplate of BaseObservable?
Don’t like ObservableField breaking your encapsulation(by making fields writeable from outside), and making them nullable?
Use DataBindingObservable from SecretSauce library via Kotlin delegate.
Before (as BaseObservable):
class User extends BaseObservable { // Fields are null before they are set private String firstName; private String lastName; @Bindable public String getFirstName() { return this.firstName; } @Bindable public String getLastName() { return this.lastName; } // If you want fields to be settable only from ViewModel those setters cannot be public public void setFirstName(String firstName) { this.firstName = firstName; notifyPropertyChanged(BR.firstName); } public void setLastName(String lastName) { this.lastName = lastName; notifyPropertyChanged(BR.lastName); } }
After:
class User: DataBindingObservable by DataBindingObservableImpl() { @get:Bindable var firstName: String by observable("initial first name value", BR.firstName) private set @get:Bindable var lastName: String by observable("default last name value", BR.lastName) private set }