Example of Realm with MVP and Dagger

Mateusz Budzar

Mateusz BudzarAndroid Developer

More and more complicated

In my previous article I’ve shown you a simple example of how to use Realm database. However projects that we are working on are definitely more complicated. We use different libraries like ButterKnife, EventBus, Retrofit, Dagger and so on. We also try to make our app more testable i.e. with the use of MVP pattern. All these things should make our life easier, sure, but it’s not that obvious how to implement it correctly – especially for the first time. In below example I tried to use Realm database in app with MVP architecture and Dagger library.


What the app can do?

  1. List all books.
  2. Add new book.
  3. Show book’s details.
  4. Show all publisher’s books.
  5. Show all author’s books.


Model consists of three simple classes.

Using Realm

According to the documentation:

This means that on the UI thread the easiest and safest approach is to open a Realm instance in all your Activities and Fragments and close it again when the Activity or Fragment is destroyed.

That’s what we’ll do with Dagger and MVP.


I used Dagger, among others, to get Realm instance for each Activity. First of all Realm configuration was initialized in Application class in initRealmConfiguration() method.

Next thing is to provide Realm instance.

Now we are ready to provide Realm instance to each Activity. ApplicationModule also provides RealmService object but about that later.


With the use of MVP pattern we try to make our views like Jon Snow – they should know nothing. Views should take care only to show something on screen or get taps and pass them on. Without ‘thinking’ and any logic. So views shouldn’t know about Realm instance either. We have to pass Realm instance to Presenter but dealing with database directly in it could be a huge burden. RealmService solves the problem.

The code of BooksActivity is shown below.

What that code is doing?

  • Initialize adapter and RecyclerView in initList().
  • Manage the View in presenter in onStart() and onStop().
  • Show books in showBooks(…).
  • Get taps in onBookClick(…) and onAddNewBookClick().
  • Go to another views in showBookDetailView(…) and showAddNewBookView().

For now don’t bother about Presenter injection and closing Realm instance. How Presenter and View interfaces look like?

The BooksActivity implements BooksView and implementation of BooksPresenter is shown below.

As you see, Presenter handles the clicks and shows all added books using RealmService. Let’s do a quick look at the BaseActivity and than we go to RealmService.

Injection and close Realm

The BaseActivity is responsible for injecting modules and forcing inheriting Activities to implement closeRealm() method.

Now we open Realm instance in onCreate() and close it in onDestroy() – as it was said in documentation.

BooksModule simply injects BooksPresenter with RealmService to the BooksActivity.


As long as we do read queries we are allowed to do them on UI thread and use injected Realm instance field.

The problem occurs with database modifications like write or update. If write operation is not a simple one we should do it on background thread.

We can either use an AsyncTask and in doInBackground() make write operation with new Realm instance between Realm.beginTransaction() and Realm.commitTransaction() or use method Realm.executeTransaction(…).

The first idea is not a good one for our architecture. All database operation should be doing outside the View, so the AsyncTask should be implemented in Presenter or some kind of service, but we also don’t want Android framework in any classes except Views.

Therefore let’s try the second solution.

Method execute() is called in background thread. If there was no exception during operations on database then onSucces() method is called, if not – onError(…). Notice that in execute() body the new instance of Realm is used.


It is possible to use Realm in MVP architecture. Even if we can’t use Realm instance in different thread than it was created, we can use async transactions mechanizm with callbacks which Realm provides. Opening and closing Realm instance in each Activity and Fragment is not a problem as long as we use Dagger and some base component which views have to inherit.

Do you have any other ideas how to use Realm with MVP? Feel free to comment.


The post is written by Droids On Roids Team Member.
We would love to take care of your app.

Leave comment

  • evan

    thanks @Mateusz for this nice tutorial!
    great work
    but why you still using dagger 1, i think that dagger 2 is more flexible and easy to setup …

    • Mateusz Budzar

      Thanks! Yeah, I know… I haven’t used dagger 2 yet so I decided to write this example with dagger 1. But I hope that despite this the example is still helpful.

  • lessfull

    What about using RxJava instead of AsyncTask? It’s more flexible and consice.
    Also is there the real need to create Presenters’ interfaces? One more file of code with no real need (I can’t image the case where it will be useful)

    You mentions Retrofit. So the models you created will be instatiated by API layer? If it’s so, than why is it permissible to use something like “private RealmList books;”? In my work every api returns id/ids, not fully-fledged objects (all my api returns json with depth 1)

    • Mateusz Budzar

      Thanks for comment!

      Of course you can use RxJava but I didn’t use it in purpose. I just didn’t want to make the example unclear because of RxJava and wanted to talk about Realm with RxJava in the next article.

      Presenters’ interfaces are useful if you want to have a few implementations of the Presenter. Thanks to that you can switch the behavior in an easy way i.e. with the use of factory design pattern.

      If you use RxJava, the Json with ids it’s not a problem. You can make the request to API and retrieve needed data from database and pass them to adapter as RealmList. You can also talk with API team about the structure of Json response and make it like your model. I usually work with APIs that return not ids but full objects and I guess that Gson library (which Retrofit also uses) was created for this reason. It is very convenient especially if you implement the ‘API browser’ type of app which mostly just shows the data from API.

  • Fábio Carballo

    Hey @mateusz_budzar:disqus ! I loved the idea. Just have one doubt? Don’t we have to call close on Realm? At least, according their guidelines we should call it.

    • Mateusz Budzar

      Hey @fbiocarballo:disqus ! Thanks.

      Yes, you are right and in above example I also call close() method on Realm in RealmService class.

      • Fábio Carballo

        Ah now I see it. However, I see you closing it when an activity/presenter is destroyed, but I don’t see you “opening” it or getting a new instance. After closing won’t be that Relam instance closed? As it is a Singleton through the use of Dagger?

        • Mateusz Budzar

          Through the Dagger I’m not passing a Singleton. There is no Singleton annotation in ApplicationModule so after close you will get a new instance of Realm.

          • Fábio Carballo

            Ah, great!

            Do you know if there is anything bad in having a singleton realm instance through the lifecycle of the app? Following the idea of having a Realm instance provided with the @Singleton annotation.

          • Mateusz Budzar

            You cannot provide Realm instance as singleton in application module, because when you close that instance in one activity you won’t be able to use it in another. You will then inject close instance and get an exception.

  • Aiman Baharum

    Well articulated and helpful article! Do you have any plans on upgrading to Dagger 2 for this?

    • Mateusz Budzar

      In fact I did, but in some way I totally forgot about it… In the near future you can expect upgrade with Dagger 2 🙂

  • Олег Герасімов

    As far as I see this approach has problems with passing RealmResults to View.
    View depends on Realm and it’s bad because
    1. it makes testing harder
    2. when we’ll remove Realm dependency (in order to use another ORM) we’ll need not only revrite code inside Model also it’ll highline View’s code
    Also View can modify databse via RealmResults.
    I may be wrong so correct me in this case please.