USING REALM ON A MVP PROJECT

This blog is from the Android development perspective.

Realm is an open source NoSQL multi platform database. It’s simplicity and transaction speed has made it a very popular database for mobile applications. From the perspective of the end-users, Realm provides many appreciated features. Realtime functionalities and offline experience are faster and easier to build.

 

SIMPLICITY

A class will be bound to Realm database by extending from RealmObject. No need to tag the attributes, Realm will do the code generation for you.


Now any object of type Person can be saved into the database.


Line 1 creates an object that is attached to the database. On line 2, while the the object attribute is updated, the database will be updated at the same time (I am not showing the transaction for simplicity, but it is needed). This is one of the features that makes Realm.io so simple (auto-update objects).  This feature is also used on objects retrieved from a query as shown in the code below:

After this query the application can change firstJoe attributes and these changes will affect the database.

Although this auto-update feature creates very simple to read and easy to update code, this also creates a big problem when your application is following the Model View Presenter (MVP) pattern.

 

REALM.IO AND MVP

As the MVP pattern states, the separation between Model, View, and Presenter attributions is key.

As stated before all objects queried from Realm database is attached to it. This tight connection with the Model will create cases where the Presenter needs to edit an object value that is attached to Realm. In this case you will have a 3 options:

Ignore the MVP “rules” and add a transaction to update the object on the Presenter
  • This option is the easiest, but it stops following pure MVP. Also testing might be challenging.

 

Send the object to the Model to be updated and receive it back updated
  • This will, in a way, maintain the MVP pattern and the Realm live object. However, the code complexity will be increased.

 

Detach all objects resulting from queries
  • This option is the recommended if you want to use both Realm and MVP in your project. The drawback is that one of the biggest features of Realm, live objects,will be lost.

 

CONCLUSION

Realm is still a great database even if you decide to detach all objects and miss on the live object feature. It is fast, reliable, and full of other features.

Tilaa blogimme