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;

   public String getFirstName() {
       return this.firstName;

   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;

   public void setLastName(String lastName) {
       this.lastName = lastName;


class User: DataBindingObservable by DataBindingObservableImpl() {
    var firstName: String by observable("initial first name value", BR.firstName)
        private set

    var lastName: String by observable("default last name value", BR.lastName)
        private set
  • Darek