Room basics – ViewModel

Reading Time: 5 minutes

In this chapter of the Room basics tutorial we are going to talk about how we can use the Room queries through a ViewModel. It means, we are going to call the queries from the ViewModel to follow the MVVM design pattern.

We can use the ViewModel as a communicator between the user interface and the repository. It holds the data in a lifecylce-conscious way, which survives configuration changes.



If you haven’t done the previous chapters, then from GitHub you can download the starter project for this chapter.

GitHub – DaoDatabaseEntity branch


Frist of all, we should talk about ViewModel a bit, especially if you are’t familiar with it.

ViewModel has many important benefits, but here we are going to talk about about three of them.

First is the above mentioned lifecycle consciousness. It means, when Android recreates the UI (eg the user rotate the device), the data won’t be lost or shouldn’t be fetched again, because the data is still available in the ViewModel.

Second, in the previous chapter we have talked already about LiveData. It has a big benefit. We can put data inside of the LiveData, then observe it in the UI. It means, when the data changes, then the UI will be automatically notified about the changed data.

Third benefit is, that ViewModel has its own CoroutineScope. As an extension function of the ViewModel, AndroidX lifecycle-viewmodel-ktx library ads a viewModelScope. So, we can call the suspended functions to separate them from the worker thread. In this case, the user intface won’t be frozen, when we do a long running task.

Step 1 – Implementation of MyApp

Before we can start the implementation of the ViewModel, we are going to create an application wide class.

In this class, we will have a singleton instance about the application context. Remember? We need a context to create the Room database.

And why do we use the application context? Because in this case we won’t hold any references about the UI, which is not a good practice.

So, click on the package of the project with the right mouse button. From the quick menu select New, then Kotlin file/class and name the new file as “MyApp”.

Then, the file should look like below.


Note that, we have extended the class by the Application class. It is a base class for maintaining global application state.

In the very last chapter, we talked about how we can create with companion object singleton variables, methods. Using the same logic, we are going to create inside of it an applicationContext() method. In the next step, we can call this method to create the Room database.

Before we can start using this new class, we have to specify it in the AndroidManifest.xml‘s <application> tag. You can find this xml file in the manifest folder.

Open it, and paste there the below line into the <application> tag.


Step 2 – Implementation of ViewModel

Next, we are going to create again a new package for the ViewModel. So, from the left Project tab, click with the right mouse button on the name of the project’s package, then select New, then Package. In the popup window name it as “viewmodel”.

In this viewmodel package create a new Kotlin file and name it as “ToDoViewModel”. The process is similar, but from the New quick menu select the Kotlin File/Class option.

Before we are going into the detailes of the ToDoViewModel::class, copy and paste the below code into our new file.


Now go through the code.

      • We have two member variables. The first one is the repository, the second one will hold the list of the ToDos
      • This list is a LiveData. When it is changing, the observer in the RecyclerViewFragment::class going to be notified and the RecyclerView will be updated.
      • In the init{} block, we will create an instance about the DAO using the ToDoRoomDatabase::class, then we can initialize the toDoRepository.
      • Still in the init{} block, we fetch the list of the ToDos, if we have created any items previously. This will ensure for us, thet the RecyclerView will be populated, when the app starts and also when something has changed in the list of our todos.
      • The rest three methods are the database operations. Note there the above mentioned viewModelScope, where we can call the suspended functions.

Step 3 – Start using Room

We have already everything created to start using them.

Create and update items

First, we are going to add the ToDoViewModel to the AddToDoDialog. So, open it from the fragments folder.

To start using the ToDoViewModel, we have to make an instance about it. 

Copy and paste the below line before the onCreateView() method.


Now, navigate to the click listener of the btnAdd Button.

There we have an if-statement, which checks the toDo variable. Remember? This dialog is responsible to create and modify ToDos. When we want to modify an existing item, then this variable won’t be null, otherwise it is null.

Paste the below line, when the toDo variable is not null.


… and this line, when it is null.


Note the createToDo() method. This method will create from the input fields a ToDo instance, whose id is 0 (zero). It has to be, because of the autgenerated primary key.
Delete items

To delete an item, we can just swipe to left or to right the items in the RecyclerView. In the preparation chapter we have already added this feature to the RecyclerView in the RecyclerViewFragment::class. So, open it from the fragments folder.

First, paste again the below line into the beginning of the class.


Now, go to the onSwiped() method of the itemTouchHelper Callback and paste there the below lines.


First, we have to figure out the position of the touched item, because we have to get this item from the adapter. We can delete this ToDo item only after that .

The observer

The last thing, what is still missing, is the observer of the LiveData from the ToDoViewModel::class.

Copy and paste the below lines into the end of the onCreateView() method.

The observer

Note that first, we are going to get the list of the already created ToDos and add them to the adapter. Thenafter, we are going to notify the RecyclerView about the changes.

Run the app

Finally, it’s time to test the app. Try to create new ToDos, then update them and delete if you don’t need them anymore.


The source code is available on GitHub

GitHub – viewmodel branch


I hope the description was understandable and clear. But, if you have still questions, then leave me comments below! 😉

Have a nice a day! 🙂



Follow and like us:
Click to rate this post!
[Total: 0 Average: 0]

Leave a comment

stay informed!

Subscribe to receive exclusive content and notifications