Realm with Koin

Aishwarya Iyer
2 min readApr 20, 2020

Realm is a database system. It’s kind of like SQLite, except it has nothing to do with SQLite at all. You define classes, these classes define your schema, and Realm stores instances of these class as objects. It’s not an SQL database, it’s a NoSQL database

What we will do here is build a same basic sample app as we did previously. If you have not read it please take a look here to understand the MVVM, architecture components and how to implement koin with it, that will help you understand this post better :)

Lets Get Started

Realm Model

Realm models are created by extending the the RealmObject base class

The open annotation on a class allows others to inherit from this class. By default, all classes in Kotlin are final

For simplicity sake again I am adding only one model class here

Next step. Create a simple Dao Interface

Let’s go for implementing Koin but wait there is a problem!

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.

If we create a singleton instance of realm and inject instance on main thread, accessing it on a computation thread will produce exception. And since database operation should be doing outside the View that means it is a problem

To solve the problem, we will not inject Realm instance. We only need to modify the DAOImpl layer to create realm instances every time and also handling the closing of it

In this way, We are no longer injecting Realm, but instead opening a new instance every time we need it. In add(), we open the instance, then the write operation, then immediately close the instance to avoid memory leaks

Koin will be used to provide dao class to repository or any other classes which needs to perform database operations and they can use a different thread to perform database operations

So our Koin databaseModule will look like this:

Let’s take a look at repositoryModule also:

Now lets initialize Realm Configuration in our Application class

Now we will use it in our Repository layer the same way we have done it in my previous article

Conclusion

What we learned here is few main things:

  1. It is possible to use Realm with Koin and MVVM. Even if we can’t use Realm singleton instance as it will be then created on main thread and reusing it with different thread will produce exception
  2. It is not easily possible to close the instance of realm if we inject the instance of it, we will need to do more of work for achieving the same
  3. With our approach it is easily possible to do the opening and closing of Realm instance as long as we use Koin for some basic injections

If you have any other ideas how to use Realm with Koin feel free to comment. Also don’t forget to clap if you liked my small contribution ;)

--

--