MVVM’s Model implementation in Android application. Room

What is Model in MVVM architecture?

As we said in the previous article Model is the data in our application. These are classes representing objects that we persist in our database or that we get from network calls to services. It is another name for the domain objects.

Persisting data locally in Android application

When it comes to persisting data locally in an Android application the only options are SharedPreferences and SQLite database. However SharedPreferences are good for storing user settings but they are not created for persisting large sets of data or relational data. So the only option for this kind of data is SQLite. Everybody who has previously used SQLite knows the pain of manually writing SQL statements for fetching and persisting data from the database, creating the tables manually, creating cursors for reading the data back and manually parsing the returned records to objects from our Model. Here Room comes to rescue.

What is Room?

According to the official documentation “Room is a persistence library which provides an abstraction layer over SQLite for more robust database access while harnessing the full power of SQLite”. With that being said it is a great tool for object mapping. This means that instead of creating objects in our Model and then creating database tables corresponding to the objects using SQL syntax we can just use POJOs for both the Model and the database tables. Room makes this process very easy introducing annotations. It handles all the logic behind for creating SQL tables and it even comes with out of the box implementations of the basic CRUD operations. And one of the greatest things is that it exposes observables used in reactive programming. It also runs most of the queries exposing observables on a background thread and this way the UI is safe from lagging. So to conclude the main benefits of using Room in Android projects are:
  • Using POJOs with annotations for schema for creating database tables
  • Automatic object mapping from database records to POJOs and vice versa
  • Out of the box implementation for the basic CRUD operations
  • Exposing observables as query results – reactive programming
  • Running CRUD operations on a background thread
Share :
Share :

Weitere Beiträge

View in the MVVM architecture

The View component in the MVVM architecture are the UI controllers – Activities and Fragments. They should be as free as possible from any business logic. Their role is to present the data, not to transform it.

Weiterlesen »
View Model. Example

In this article we will go through the steps of creating a simple game screen. We will make it the traditional way without using View Model and we will see why it is absolutely wrong to persist data in the View.

Weiterlesen »