Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewModel and Data Binding

Tags:

android

Android has recently introduced Architecture Components and in particular a ViewModel, which is

designed to store and manage UI-related data so that the data survives configuration changes such as screen rotations

In example provided by Google, ViewModel is used like this:

public class MyActivity extends AppCompatActivity {
    public void onCreate(Bundle savedInstanceState) {
        MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);
        model.getUsers().observe(this, users -> {
            // update UI
        });
    }
}

Question: How does ViewModel suppose to correlate with the Data Binding?

I mean, in case of data binding there is going to be a binding which provides data for the UI.

Is it going to look like this:

...
model.getUsers().observe(this, users -> {
  // update binding, that will auto-update the UI?
});
...
like image 818
0leg Avatar asked Jun 08 '17 17:06

0leg


1 Answers

You can declare a variable of your viewmodel type in your layout xml file. In your viewmodel class implement public methods through which data will be bind to ui.

Then you only need to set view model into binding in onCreate. When you set view model instance in databinding, the data which is already loaded in viewmodel will be set to recreated layout.

In case there is a recycler view in your layout you can implement some public method like initRecyclerView() in your view model class and call it in onCreate() after setting view model in binding or adapter can be set from view model through databinding as well.

like image 175
dzikovskyy Avatar answered Nov 08 '22 14:11

dzikovskyy