Databinding Observable for Jetpack Compose

SeongUg Steve Jung
2 min readJun 28, 2021

--

Today, I am going to start to tell our team journey : Classic XML to Jetpack Compose.

This would not be usual story. Our team is not following Jetpack ViewModel and Hilt but Databinding and our own Lifecycle Handler.

In this posting, I will start a very small topic : co-living Databinding Observable and Jetpack Compose.

XML and Databinding Observable

In a classic way: XML (I know Jetpack Compose is not stable. But I believe it will be standard way), Databinding is one of smartest friend for XML.

We don’t need to write any native view code in Activity or Presenter level.

Simply, we can put this way.

class MainActivity {
@Inject lateinit var viewModel: MainViewModel
fun onCreate() { MainDataBinding.serVariable(BR.viewModel, viewModel)}
}
class MainViewModel {
val title = ObservableField<String>("new title")
}
// xml
<TextView android:text="@{viewModel.title}" />

It helps lots of part be omitting to access view.

I was one of big fans of Databinding. I recommended to use Databinding frequently to my team on our product.

New Paradigm : Jetpack Compose

Jetpack Compose is brand new UI Component. It has very different mechanism to old way(XML)

It could replace with Databinding 100%.

So we had discussions a few times and decided to migrate Jetpack Compose from XML and Databinding. Before starting migration, we set some rules.

Migrating Rule 1 : try to re-use ViewModel

Basically, I don’t like Big-bang release: Roll out 100%, No roll back plan. Before completing Testing/QA or stable build, I prefer to roll out runtime-staging. To approach this goal, We have to maintain both UI components.

Sometimes, maintenance period can be longer than expectation. So different ViewModel maintaining will cost a lot. So we put a rule to reuse ViewModel.

Most code isn’t needed to be change. But Databinding Observable. It is not component of Compose. What we need is to notify recomposing when data is change.

So I created interoperability code below

This is similar to LiveData.observeAsState() .

With DisposableEffect , When Compose lifecycle is activated, it observes property changing. it removes observer when disposing.

We can eventually support databinding observables in Compose.

Migrating Rule 2 : ViewModel can be tested on JVM

Conclusion

If you are using Databinding Observable, don’t be afraid to migrating. Jetpack Compose team and all contributors are open a way to support customizing.

--

--

SeongUg Steve Jung
SeongUg Steve Jung

Written by SeongUg Steve Jung

Android Developer, Google Developers Experts

Responses (1)