Wednesday, 2 September 2020

Comparison between Layout Binding and Manual Binding(with observe) in MVVM architecture of android

Using Android Jetpack components and MVVM architecture, we can get live data updates in a View from a View Model in 2 ways, one is to bind the layout with the live data variable, other way is to observe the variable in code. To illustrate my question I have taken an example. Suppose there is a view model interface getTimeString() which returns the current time.

a) Layout Data Binding

  1. The view in the layout looks something like this

        <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        ... 
        app:binder_data_date="@{sampleVM.timeString}"/>
    
  2. The binding adapter looks something like this

    @BindingAdapter("binder_data_date")
    public static void binder_data_date(TextView text, String data) {
        text.setText(data);
    }
    

b) Manual Data binding (just to give it a name): In Manual data binding, there is nothing in the layout view with respect to the binder, and I observe the live data using the observe() and update the textview.

 FragmentSplashScreenManualBindingBinding fragmentSplashScreenBinding;
SampleViewModel sampleViewModel1 = ViewModelProviders.of(this).get(SampleViewModel.class);

public void onSomeRandomFunc(...) {
 .... 
 sampleViewModel1.getTimeString().observe(getViewLifecycleOwner(), data -> {
        fragmentSplashScreenBinding.sampleText.setText(data);
    });
 }

I know the first method is much easier to use and both works.

  1. But is using the second method and the way to access the variable (fragmentSplashScreenBinding.sampleText.setText()) in fragment to update the View correct?
  2. Will the performance get impacted if I use the second method?


from Comparison between Layout Binding and Manual Binding(with observe) in MVVM architecture of android

No comments:

Post a Comment