Room Offline Database with RxJava2.

Android Room persistence library with Rxjava2 and lesser-known features of Room database

Have you ever seen loading in any of the Google apps, most of the time NO that’s because of Room library(local database for android).

Siva Ganesh Kantamani
MindOrks

--

Room & Rxjava2 can be easily linked than ever.

Need of Database in Android Apps:

No one ever said I love loading screen, yes that’s right not even developer’s. This can be even more painful when you wait to see the content that you have already seen once. There comes the solution local Database.

Local Database in Android

For data persistence in android, we have SQLite since android one. Even today SQLite is one of the most powerful databases with CRUD operations but there is a problem boilerplate code so much of it, sometimes because of that, we(or at least I) think to exclude data persistence in the app.

Room Database Library:

Under the above circumstance, we need a library which is capable of performing SQLite complex operations with no boilerplate code, that’s when Room comes handy. Room an object mapping library for SQLite, Room is an abstract layer over SQLite to provide simplified coding. Room simplifies your coding time by removing the need to write boilerplate code.

Components of Room

1. Entity :

@Entity annotation above any data class indicates as a table in the database. Isn’t it that easy, yes we can create a table in the database directly through a data class. Every field in the class is a column in the database table and we can give a specific name to that column by annotating that field with @ColumnInfo (name = “column_name”) and there should be at-least one Primary Key field.

2. Dao :

Dao -Data Access Object is an interface class with annotation @Dao, the name itself tells that this is the class which is used to access the data(@Entity) from the database. That means we can perform CRUD operations here. We just need to write a method with desired inputs and outputs and then annotate the method with respective annotation. The room supports the following annotations in Dao @Insert, @Update, @Delete, @Query.

3. Database :

This database contains all the tables and can be created with an abstract class with @Database annotation. The attribute version is used to define the database version and entities are used to define the list of entities this database will contain as tables.

Now lets do some coding

Step 1 :

Integration of Room: Integrating room database with AndroidX, Kotlin and Rxjava support with latest versions at the moment.

Step 2:

Now we’re gonna create a tv-show tracking app with an Entity class which creates a table in the local DB then a Doa class to access content in DB.

As I mentioned above Entity class create a table in the database and each variable in it creates a column, let’s have a look

As Kotlin is the primary language for android, this code samples will be written in kotlin. As I mentioned earlier @ColoumnInfo is used to give a name to that column in DB. There should be at least one @PrimaryKey whose value should be unique.

Step 3:

Now we have a table in DB the next step is to create a Dao class to access the contents in the table.

As I mentioned above Dao is a class used to access the data in the DB that’s the reason why each method in the class is annotated. @Query, @Insert, @Delete, @Update are Room annotations which will help you in content management.

@Query annotation will help you to write data related SQL queries. As you observe properly @Insert has a param onConflict which is useful when you try to insert a column with a key that was already in the table, OnConflictStrategy has three options ABORT, REPLACE and IGNORE

ABORT : Abort the transaction. The transaction is rolled.

REPLACE :Replace the old data and continue the transaction.

IGNORE : Ignore the conflict.

Step 4:

At this point, we know how to create a table in the database and how to access the data from it. Now to access any of this we should have a RoomDatabase instance. For that first, we have to create a class which extends RoomDatabase as shown below.

RoomDatabase extension class has two annotations @Database(mandatory) and @TypeConverters(optional)

@Database:

TThis annotation has two variables one is entities through which we can tell how many tables should be in RoomDatabase and the other is TypeConverters which is optional that which allows you to persists a specific custom type into a database. A class can have as many @TypeConverter methods as it needs. Each converter method should receive 1 parameter and have a non-void return type. It converts from an unknown type into a known type in terms of database types.

Using TypeConverters in the above sample we convert date to long while storing into the database and when retrieving room converts long to date then return the desired datatype.

Get application database instance as shown below

ApplicationDatabase.getInstance(context)

Step 5:

At this point, we have created tables in the database, data access classes and obtained RoomDatabase instance to operate. It’s time to use RoomDatabase in our code.

If we observe in step 3 example @Update, @Insert and @Delete has same return type which is Completable(also support Single<Long> and Maybe), so those three can be accessed similarly only difference is params passing to those methods.

With magical Rxjava you can easily access the database as shown above.

subscribeOn(Schedulers.io()) will take care of accessing the database only in the background thread.

observeOn(AndroidSchedulers.mainThread()) will take care to return the result on the main thread.

We can do @Update and @Delete operations similarly to @Insert as shown above.

Now how to get data from tables(@Entities), in step 3 the sample Dao has Single as the return type for-get methods that means all get methods can be handled similarly. I’ll show a sample piece of code how to getAllShows().

That’s it now we know how to create tables in the database, how to access data from the database and how to handle Dao methods with Rxjava2.

Tips on how to user Room efficiently

Tip 1

You have leverage of inserting single item, Array of items or a variable number of items into the database in a single attempt as shown below.

This is the same case with @Update and @Delete.

Tip 2

Until now I have shown you how to insert primitive data types which are accepted by SQL into room database, this might not be the case in all situation, Let’s say there is a data class as a variable in your entity, to be clear I’m posting code below.

let’s say there is a LeadActor data class which contains name,role and Id of an actor.

Now we have a tv show entity with all the basic info and LeadActor as shown below.

If you observe TvsShowsEntity properly you will see a new annotation @Embedded which is used to store data-types(LeadActor) that are not supported by SQL directly.

Tip 3

What happens when we have multiple columns with the same data type and annotated with @Embedded. In this situation, it throws an error because SQL won’t allow duplicate column names, for this we need to add prefix attribute as shown below.

Now let’s see what happens internally

Following are the variables that are stored in the database for lead_actor

  1. actor_id
  2. actor_name
  3. actor_role

and for female_lead_actor the variables are

  1. female_actor_id
  2. female_actor_name
  3. female_actor_role

Tip 4

For this one to understand you need to know what is live data and how it works. Using LiveData to observe data from the room-database, which is very useful to keep your app reactive with data changes either from user or servers. This doesn’t need any explanation just have a look

LiveData in Dao
Observing live data from Room

It’s that simple now every time data changes live data invokes the updated data and you can update UI. For Rxjava fans Flowable is supported.

Watch one of the early presentations of Room in youtube, it has everything you need to know if you’re new to Room library.

Read the medium articles from Florina Muntenescu which are worth of time if you’re learning Room.

To know more tips like above on android development and architectural components follow me on Medium & MindOrks.

Also you can find me on Medium and Twitter and LinkedIn Cheers!

Thanks for reading.

--

--