How I learned Realm Asynchronous and Synchronous Transactions

Published Jan 21, 2018
How I learned Realm Asynchronous and Synchronous Transactions

About me

I am Bapusaheb Patil, and I am a self-taught Android developer, and I am Udacity/Google-certified Android Developer Nanodegree Graduate. I love building apps that have a great balance of minimal elegant design and great functionality.

Why I wanted to learn Realm Asynchronous and Synchronous Transactions

I wanted to Realm because it was a great replacement for SQLite for most of my apps.
And in Realm, I think it's helpful if I dive deep into asynchronous and synchronous transactions, since this topic is barely touched by any guide/tutorial on the Internet.

How I approached learning Realm Asynchronous and Synchronous Transactions

I learnt asynchronous and synchronous transactions in Realm via the official documentation and implemented them in 3 of my apps.

Challenges I faced

Calling a Realm transaction from a wrong thread can cause your app to crash.
Knowing when to call it from which thread without the Realm instance getting closed or the app crashing because Realm took too long to run on the UI thread was one of the main challenges me and a lot of other people in the community were facing.

Key takeaways

I loved solving this problem. It was so grueling and exhausting and made me pull my hair a few times, but I have finally figured it out.
Basically, when you perform a transaction, you should only do synchronous transactions if the data you're transacting isn't so big that the transaction blocks the main UI thread. But doing so on a background thread may cause Realm to close. So it is advised to have a callback on the main UI thread and perform an asynchronous Realm transaction there. That way, the Realm instance that was opened on the main UI thread won't be closed until the Activity is destroyed and since the transaction is running on another thread, it'll work just perfectly.
More info on what I'm talking about can be found here:

Tips and advice

I suggest you take a thorough look at the official documentation and the Issues section on GitHub for Realm.
And if something in Realm doesn't work for your app, find a work-around for it, there is no need to ditch Realm just because you couldn't get a small thing in your app working with Realm.

Final thoughts and next steps

This experience made me more comfortable using Realm and gave me a deep knowledge of it. Realm is 10x faster than SQLite and I think it has the potential to replace SQLite in the coming years, provided development on it is steady and is making progress.
I would also look into Room by Google though, at this point. Since it's by Google and provides a great interface for database operations.

Discover and read more posts from Bapusaheb Patil
get started