Open In App

Overview of Data Binding in Android Architecture Components

Improve
Improve
Like Article
Like
Save
Share
Report

This article describes the idea behind the Data Binding and MVVM design pattern and its components. If you would like to experiment with it hands-on, open an old project with spaghetti code. If you don’t have one, you’ll get one from GitHub. Then, attempt to use the MVVM components introduced during this article.

In some ways, software development hasn’t changed much within the last decade. the essential challenges remain the same:

  • Writing clean code.
  • Having a versatile architecture.
  • Testing the code.
  • Creating an excellent user experience.
  • Developing features faster than product management can consider them 🙂

All these problems had an answer by the time Android entered the market. Desktop and web application developers already had a knowledge domain for writing user interfaces. Those solutions worked for Android too, but they were far away from ideal.

Android initially supported Java and apps were typically implemented using MVC (Model View Controller). Ten years later, there’s Kotlin…& there’s MVVM along with Data Binding. Hence, had been an extended journey over those ten years, so let’s catch up!

Using DataBinding

Data Binding as a single term refers to the technique that connects data from end consumers and users and then keeps them in sync. Android’s Data Binding Library lets the developer keep the UI within the layout XML files and generates code from them. The library also does the work of synchronizing the View with data that comes from the ViewModel. In order to add data-binding to your vanilla android project, you will need to add the following lines to your app’s build.gradle file:

android {
...
dataBinding {
  enabled = true
  }
}

After making the dataBinding element ‘true’ you will need to add this to your XML file like:

XML




        xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
        <variable
            name="user"
            type="com.geeksforgeeks.example" />
    </data>
    <ConstraintLayout... /> <!-- Your UI layout's root element -->
</layout>


After adding the above code into your XML you can use LiveData to notify the UI about data changes:

Differing from objects that implement Observable elements like: Observable Text Fields, the Live Data objects realize the lifecycle of the observers subscribed to the info changes. this data enables many benefits, which are explained within the advantages of using LiveData. In Android Studio version 3.1 and better, you’ll replace observable fields with LiveData objects in your data binding code.

Java




class ViewModelActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
            
          // Inflating the view to obtain an instance
        UserBinding binding = DataBindingUtil.setContentView(this, R.layout.gfg);
  
        // Specifying the present (current) activity as the parent
        binding.setLifecycleOwner(this);
    }
}


Kotlin




class ViewModelActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        
      // Inflating the view to obtain an instance
      val binding: UserBinding = DataBindingUtil.setContentView(this, R.layout.gfg)
          
      // Specifying the present (current) activity as the parent 
      binding.setLifecycleOwner(this)
    }
}


Why Binding to LiveData?

The advantages of employing lifecycle aware components like LiveData include:

  1. No crashes thanks to stopped activities. If the observer’s lifecycle is inactive, like when an activity is within the back stack, then it doesn’t receive any LiveData events.
  2. Proper configuration changes. If an activity or fragment is recreated thanks to a configuration change (for instance, device rotation, angle changes, etc), it immediately receives the newest available data.
  3. No memory leaks. No got to dispose of subscriptions manually. The observers pack up after themselves when their associated lifecycle is destroyed.

A Word of Warning

Be careful to not introduce infinite loops when using two-way data binding. When the user changes an attribute, the tactic annotated @InverseBindingAdapter is named. This, in turn, would call the tactic annotated @BindingAdapter, which might trigger another call to the tactic annotated @InverseBindingAdapter, and so on. For this reason, it’s important to interrupt possible infinite loops by comparing new and old values within the methods annotated @BindingAdapter.

Some Final Thoughts

The Lifecycle of Android components is complex and may be a pain to manage manually as keeping the UI up-to-date with data sources, therefore introducing LiveData, maybe a huge intensify in lifecycle management. Adding data binding into the project can make code more concise and reactive during a sense that changes in data sources are often propagated automatically to the UI taking into consideration the configuration and lifecycle state. However, you using Data Binding Library shouldn’t be limited by only setting a knowledge model’s properties into text fields. Binding to LiveData with one- and two-way binding will allow you to form the foremost of the Observer pattern and lifecycle awareness.



Last Updated : 09 May, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads