Android Architecture Component with Room database,View Model and Live Data
This sample showcases the following Architecture Components:
This sample contains two screens: a list of delivery and a delivery detail view.
The presentation layer consists of the following components:
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:
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.LiveData
objects. Because LiveData
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:viewModel.getDeliveryList().observe(this, new Observer<List<DeliveryDataModel>>()
{
@Override
public void onChanged(@Nullable List<DeliveryDataModel> deliveryData)
{
// Update the UI.
deliveryArrayList = (ArrayList<DeliveryDataModel>) deliveryData;
recyclerViewAdapter.addItems(deliveryArrayList);
}
});
Room populates the database asynchronously when it's created, via the RoomDatabase#Callback
. To simulate low-performance, an artificial delay is added. To letother components know when the data has finished populating, the AppDatabase
exposes aLiveData
object..
To access the data and execute queries, you use a Data Access Object (DAO). For example, a product is loaded with the following query:
/**
* Fetch all delivery item from the database.
*/
@Query("SELECT * FROM DeliveryDataModel")
LiveData<List<DeliveryDataModel>> fetchAllData();
/**
* Counts the number of items in the table.
*
* @return The number of delivery list.
*/
@Query("SELECT * FROM DeliveryDataModel where slNo = :slNo")
Cursor getDeliveryById(int slNo);
Queries that return a LiveData
object can be observed, so when a change in one of the affected tables is detected, LiveData
delivers a notification of that change to the registered observers.