How to use LiveData with Realm

If you’re an Android Developer and haven’t been living under a rock since Google IO’17 you’ve undoubtedly seen a lot of excitement and numerous blog posts regarding Android Architecture Components.

There is indeed a lot to be excited about regarding the power and utility of these new components (ViewModel, Lifecycle, LiveData and Room).

Live Data Streams

From my perspective, LiveData is the most exciting part of the line up. It’s awesome to see Google now embracing the concept of live, auto-updating, data. It’s equally awesome to see how they’ve integrated LiveData right into the new SQLite ORM (Room).

This makes it easy to see the power of LiveData right away, but what I love most about the design of LiveData is that Google has made it generic and open for developers to use LiveData for a variety of other use cases such as:

Realm + LiveData

The flexible nature of LiveData allows it to be easily integrated into other 3rd party libraries too! As an engineer at Realm, this is very exciting for me because it means that I can wrap RealmResults as LiveData and use it as I would any other piece of LiveData.

This has at least two additional benefits.

It makes it even easier for developers to react to data changes as they no longer have to register a changeListener for RealmResults in their Activities onStart() method and unregister it onStop(). Rather this can happen automatically with Realm-LiveData when the owning Activity starts and stops observing it.

The second benefit is that it allows RealmResults to participate in LiveData Transformations. Transformations are great because they allow you to transform any LiveData from something very specific, like LiveData<RealmModel>, at your Repository or ViewModel layer, to something completely agnostic of the underlying source, like LiveData<String> at the Activity Layer. You get this without giving up the Live Auto-Updating nature of Realm. This keeps the various layers of your app isolated, which makes them easier to compose, update and test.

Getting Started

For a complete how-to guide and sample project on how to integrate Architecture Components into Realm, check out this other post I wrote, but this quick example should give you the general idea to get started.