Room Persistence Library in MVVM Architecture| Kotlin

The rights of this image are for RayWenderLich
The rights of this image are for RayWenderLich

What is Room Persistence Library?

Implementation of the Room

Now we are ready to create our own local database tables.

How to create tables on Room DB?

  1. Entity
  2. DAO
  3. Database

Let’s start with entity class

Entity

In the example below, @Entity(tableName = “shopping_list_table”) annotation allows us to create a table with the given name. Following, to create our columns and data types of the columns. In the last part of the class, we initiate primaryKey columns and automatically increase the entity in the column with “(autoGenerate = true)” — a part of the annotation.

DAO

If you look carefully at our query method, you will notice the LiveData data type. As mentioned in the first paragraph of the Room description, LiveData lets us observe the data, which returns from that query. One of its advantages is no Memory Leak. We shouldn’t confuse it with Observable.

LiveData is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state.

As we remember, we implement 2 more different dependencies to the app/build.gradle file, which are lifecycle dependencies. The reason of it to use LiveData in our project.

Database

Finally we have done with building our local database. As you see, if we understand the logic, the Room is quite a simple library to implement.
Let’s push it and see, how we can write/read on the runtime or create mock data to test our project.

TypeConverter

Room provides functionality for converting between primitive and boxed types but doesn’t allow for object references between entities.

Because of this issue, sometimes we need to convert our data types between each other.

MVVM Architecture

We will build our project according to MVVM Architecture, which means,
we will have:

  1. Model(Data)
  2. View(UI)
  3. ModelView(Helper class to access the Model trigger via UI)

Model

First thing first, if we create a folder whose name is “data” and put all the classes we have created, it will be much easier to see the architecture.

View

As an example:

ViewModel

ViewModel is a class that is responsible for preparing and managing the data for an Activity or a Fragment. It also handles the communication of the Activity / Fragment with the rest of the application (e.g. calling the business logic classes).

After all these, it’s all on you to use these methods and design your own app, how you want.

I hope you enjoyed it.