Data Binding inside Anko Components ? Why not.

Oh you sweet sweet thing — ObservableProperty. Kotlin is ♥️

Arnav Gupta
Coding Blocks
3 min readDec 4, 2018

--

Image result for android databinding
Data Binding — making mobile developers feel as good as web developers since 2017

Let’s first see where we will get with this. 23 lines of code, and magical data binding is here in Anko Layouts.

2-way DataBinding — that sweet thing that web developers had been enjoying for decades

So what gives ? Well, we need the following things to get here.

  • Kotlin’s ObservableProperty delegate.
  • Adding an inline extension function to TextView

ObservableProperty and what it means ?

One thing, I keep reminding people every other day is, Kotlin isn’t any sort of black magic. When using with Android/Java Kotlin is nothing more than some extra-sweet syntactic sugar. So what is ObservableProperty , well, nothing supremely superior to Java Observables or RxJava observables. But, there are some niceties. You should probable check these excellent blog posts out too [1][2]

So I extend ObservableProperty and create a StandardObservableProperty which has a value (which is the backing field containing my data) and we can add valueChangeListeners

Creating StandardObservableProperty

Now we need the helloworld = hello + world effect, for which I created an ObservableReducer

The bindString extension

Next what we need is the bindString extension in TextViews that lets me do these

So what we add extension functions that binds a StandardObservableProperty to a textview. When the observable changes, we update the text in textview, and when the TextWatcher in the TextView is updated, we update the Observable. Keep in mind the setSelection(start+count line, because that makes sure our cursor does not jump around on the screen.

2-way binding setup inside Anko

Now we can use this in our Anko layout. Simply use bindString() to attach an ObservableProperty into a textual field.

Since the ObservableReducer is also extended from StandardObservableProperty it can also be passed into a `bindString` call.

And voila, we have our 23-line magical code here.

Changes in the two editText’s will update the text in the textView

--

--

Arnav Gupta
Coding Blocks

Swimmer, Coder, Poet, Engineer, Entrepreneur. Co founder of Coding Blocks. Mobile Platform at Zomato