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?
});
...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With