Implementation of Room Database in Android with help of Rx Java

Room provides an abstraction layer over android SQLite to allow fluent database access in case of changing or adding schema in the query.

Problem Statement - There is no compile-time verification of raw SQL queries. As your data graph changes, you need to update the affected SQL queries manually. This process can be time consuming and error prone.

  • You need to use lots of time to identify error & modify SQL queries.

Solution - Room takes care of these concerns for you while providing an abstraction layer over SQLite.

There are 3 major components in Room:

  • Database: You can use this component to create a database holder. The annotation defines the list of entities, and the class’s content defines the list of data access objects (DAOs) in the database. It is also the main access point for the underlying connection.
  • Entity: This component represents a class that holds a database row. For each entity, a database table is created to hold the items. You must reference the entity class through the entities array in the Databaseclass.
  • DAO(data access objects): This component represents a class or interface as a DAO. DAOs are the main component of Room and are responsible for defining the methods that access the database.
Figure 1. Room architecture diagram

RxJava - Room returns RxJava2 Publisher and Flowable objects from the queries you define.

To use RxJava functionality, add artifact from the Room group into your build Gradle dependencies. You can then return objects of types defined in RxJava2.

Please follow below steps to implement Room using Rx Java

Step 1- Add gradle build dependency(app.gradle):

Step 2- Create a Object class for Database:

Step 3- Create a DAO class to define the SQLite queries :

Step 4- Create abstract class that will extend Room database and return DAO:

Step 5: Insert and retrieve the data from Room database :

By accessing database using a DAO class instead of query builders or direct queries, you can separate different components of your database architecture. Furthermore, DAOs allow you to easily mock database access as you test your app.