Should View Binding replace Data Binding?

Viewed 6072

Curently, I'm using data binding for two cases:

  • to access views in fragment
  • to subscribe data with view model in layout.

When I compare with view binding, I see both methods fine (view binding better to access views, data binding to bind data), so which pattern should be preferred for MVVM?

Should I move to view binding and handle ViewModel-layout connections in fragment only?

3 Answers

For your question Should View Binding replace Data Binding, the answer is it depends on the usecase.

The ViewBinding only generates the ViewBinding of your layout files, so you can refer to the views without using findViewById.

The DataBinding provides you the same but with extra functionalities like data-binding expressions (putting common Java logic in XML), common data variable for whole xml, annotations, etc.

So when to use these?
In case you just need to access views in your Java code without any complex/repeating view logic (eg: change visibility of multiple views on basis of one data variable), then you should use ViewBinding as it is lighter and faster.

But in case you need more than just accessing the views like binding expressions, binding adapters, etc. (which is general requirement of big projects). You should use DataBinding as it provide more features.

For more info, please have a look at
https://developer.android.com/topic/libraries/view-binding#data-binding - Comparison by AndroidDeveloper
https://proandroiddev.com/new-in-android-viewbindings-the-difference-from-databinding-library-bef5945baf5e - Comparison by ProAndroidDev

View binding does not replace Data binding.

View binding is intended to handle simpler use cases and you can use data binding in layouts that require advanced features.

Benefit of view binding:

  • Faster compilation: View binding requires no annotation processing, so compile times are faster.
  • Ease of use: View binding does not require specially-tagged XML layout files, so it is faster to adopt in your apps.

Limitations compared to data binding:

  • View binding doesn't support layout variables or layout expressions, so it can't be used to declare dynamic UI content straight from XML layout files.
  • View binding doesn't support two-way data binding.

Because of these considerations, it is best in some cases to use both view binding and data binding in a project.

Please have a look at the android official doc comparing view binding with data binding: Comparison with data binding

It all finally depends on your use case ,

Use Databinding if you want to set data via xml on cost of increasing build speed , Use view binding if you just want to omit findViewById , view binding is way cheaper compared to databinding . Databinding is like superset of viewbinding . You could also use both if you want .

I suggest you watch this answer by Yigit https://youtu.be/QWHfLvlmBbs?t=42 .

Related