Android’s Data Binding’s BaseObservable class and @Bindable annotation in Kotlin

Jorge Enciso
2 min readMay 16, 2017

--

In my one and only Medium post so far I have written a brief introduction about some first steps to take for using data binding with Kotlin. Now, in this new post I’m telling you how to use another Data Binding feature with the Kotlin data classes.

What is @Bindable?

If you are new to Data Binding you may not have checked out about this annotation yet. It is made to be applied to the getter of an Observable class, then it is generating a field in the BR class to react if the field value changes.

What is an Observable class and what is a BR class?

I haven’t covered this in my one and only Medium post so far, so now I’m giving a brief explanation in the next lines:

BR class is the class which is generated by the Data Binding for storing all the reactive values to handle.

Observable class. If you’re familiarized with the Observer pattern or reactive programming you may have an idea of what is it. If not: an Observable class is a class which is able to be observed by others classes, then the “observer” classes are going to react and notify when they observe any change in the Observable class… in the Implementation it is far easier than it seems, don’t you worry.

Stop this small talk, show me the code!

Alright, now I’m listing what you are finding in the snippet next:
* Item data class extending the BaseObservable class which converts our class into a brand new Observable class. Easy as that!
* The now f o r g o t t e n (? encapsulation is brought back with the private values declared in the Item’s constructor. Those private values are acceded by the getters and setters declared inside the class.
* The @Bindable annotation is used on the getters in order to mention to Data Binding that those classes are going to be binded.
* The notifyPropertyChanged() function is in the last line of every setter of every bindable getter. This function is inherited from the BaseObservable class.

That’s all the needed implementation for the data class, now every time any variable which getter has the @Bindable annotation and setter has the notifyPropertyChanged() function is going to reflect its new value in the component it is attached to.

In order to jog the memory, here is the xml to show how the Item.kt data class is linked to a View.

Now, before finishing, I want to say thanks to Dre Pilipczuk because he asked me about this topic and after answering I felt encouraged enough for writing this one second post feeling that I have something else to write about.

--

--