This sample showcases the following Architecture Components:
This sample contains two screens: a login view and a home view.
The app uses a Model-View-ViewModel (MVVM) architecture for the presentation layer. Each of the fragments corresponds to a MVVM View. The View and ViewModel communicate using LiveData and the following design principles:
- ViewModel objects don't have references to activities, fragments, or Android views. That would cause leaks on configuration changes, such as a screen rotation, because the system retains a ViewModel across the entire lifecycle of the corresponding view.
-
ViewModel objects expose data using
LiveData
objects.LiveData
allows you to observe changes to data across multiple components of your app without creating explicit and rigid dependency paths between them. -
Views, including the fragments used in this sample, subscribe to corresponding
LiveData
objects. BecauseLiveData
is lifecycle-aware, it doesn’t push changes to the underlying data if the observer is not in an active state, and this helps to avoid many common bugs. This is an example of a subscription:
// Update the list of products when the underlying data changes.
viewModel.getProducts().observe(this, new Observer<List<ProductEntity>>() {
@Override
public void onChanged(@Nullable List<ProductEntity> myProducts) {
if (myProducts != null) {
mBinding.setIsLoading(false);
mProductAdapter.setProductList(myProducts);
} else {
mBinding.setIsLoading(true);
}
}
});
The database is created using Room