Let’s move to implementation of Repository pattern and meet with another component from AAC.

Our app invokes a request to Github API and saves the result to local storage. It gives us opportunity to get existing data from a database, without a need to use expensive requests to a web service, consequently our app can also work without an Internet connection.

I chose the new Room Persistence Library as local datastore to explore it. Room provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.

Room has the following benefits:

It’s ORM and you don’t have to write boilerplate code to convert Cursor to POJO or one to SQL queries.

Compile-time verification of raw SQL queries

You can use the power of a relational database

Drawbacks:

You have to write raw SQL

It’s not as fast as NoSQL

There are 3 major components in Room:

Database

The annotation defines the list of entities and schema’s version. The class’s content defines the list of data access objects (DAOs) in the database.

To create a database in an async way, I use singleton and Builder from Room class.

We can use isDatabaseCreated LiveData to detect the moment when the process of creation will finish.

Finally, we can invoke createDb method from App class.

Entity

Represents a class that holds a database row.

There are a lot of annotations that can be helpful for you, such as @ColumnInfo(name = "first_name"), @Insert, @Delete, @Ignore, @ForeignKey and so on and so forth.

Please notice, that Entity doesn’t require empty constructor, unlike RealmObject and we can use it as a data class. However I received this error if I added more than two constructors with args.

/entities/Repo.java:51: error: Room cannot pick a constructor since multiple constructors are suitable. Try to annotate unwanted constructors with @Ignore

DAO