Building Reactive Apps with Realm: Episode 1

In this five-episode series, we’re going to have a look at how Realm facilitates building reactive applications from the ground up. In the first episode, we’ll start by creating a Swift Playground to cover the basic concepts of using Realm. We’ll create a bare bones application that writes to a Realm database, and also take a quick look at Realm’s notification mechanism.

You can find the other episodes here:


 

Introduction

Welcome to Building Reactive Apps with Realm. Over the span of a few episodes, we’re going to have a look at how Realm helps you build reactive applications with Swift. Reactive systems are responsive, resilient, elastic and message driven, as defined by the Reactive Manifesto. That is nothing really new; we’ve been building apps like this in the past.

In fact, in Swift and the iOS SDK as a whole, we have a lot of different mechanisms that allow us to build reactive apps. We have a notification center for notifications. We have a delicate pattern for sending messages. We have a simple dispatch to keep your apps UI responsive, and so forth.

Get more development news like this

The issue with those mechanisms is that using them all together often turns your app into a complex web of notifications and data polling. In this series, we’re going to have a look at how Realm facilitates building reactive applications from the ground up. We’re going to have a look at the reactive aspects of Realm, one of them is that it’s blazing fast. It always provides live data in your results and is never outdated. We’ll also take a quick look at its beautiful notification mechanism.

In this video specifically, we’re going to have a look at the basics of what do we mean when we say you always see the latest data when you read from Realm.

Realm and Adding Objects

Let’s open up a playground and make sure we understand the basics before we move on to playing with real projects in the following episodes. We’re going to have a look at the bare bones of a Realm project in a playground. My favorite way to set up a playground with Realm is through a CocoaPod plug-in that makes it really easy to do so. It’s called cocoapods-playgrounds.

Once you have it, you can go to your console and just type pod playgrounds, and then add the name of the pod you want to use in your playgrounds. This for me is RealmSwift. Once you do that, this will open Xcode automatically for you, with the playground and the proper pods included. You don’t have to actually do this. You can also use a normal app for this, I just really like using playgrounds. Let’s build our project, and once Xcode builds the pods, you can use them from within your playground.

Let’s have a look at creating a simple Realm with a single type of object. In playgrounds, things happen a little bit slower than normal. I’m going use an in-memory Realm, like so:


//: Please build the scheme 'RealmSwiftPlayground' first
import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
import RealmSwift

var conf = Realm.Configuration.defaultConfiguration
conf.inMemoryIdentifier = "Playgrounds"

let realm  = try! Realm(configuration:conf)

I will need one object to store in it, so let me add a person object:


class Person: Object {
    dynamic var name = ""
    convenience init(_ name: String) {
        self.init()
        self.name = name
    }
}

I have my person, class and my in-memory configuration in my Realm. Now I can add some objects to it, and I can query them back:


try! realm.write {
    realm.add(Person("John"))
    realm.add(Person("Sam"))
}

let people = realm.objects(Person.self)

Let’s bring the count of people:


people.count

We can see right away on the right-side that there are two objects found back, and everything is looking perfect!

Live data

Let’s do something else now, to see what I meant by “live data.” Let’s add a few more people to the Realm database:


try! realm.write {
    realm.add(Person("John"))
    realm.add(Person("Peter"))
}

Now we have four people stored in Realm. I’m not going to fetch or refresh in any way my people results. I’m going to print the count again.


people.count

You should be able to see in your playground, this time, the count is four. Again, I didn’t have to refresh. I didn’t have to reload. I didn’t have to in any way tell the results that I want to see now how many objects there are in memory or on the disk, and so forth. The results always show the latest data there is.

If you print the people right before, and after we add the third and fourth people, you will see the two objects that we stored before, and then the four objects. That is what I mean by live data. When you access your results object you always see the latest data that is stored on disk. It’s never really outdated in any way. That is live data.

The problem is that you can’t hard-wire your UI to your results so that it always shows the latest data on the screen. To do that, Realm also gives you a very handy mechanism I already mentioned on notifications.

Notifications

Any time there is any change to the results that you’re interested in, Realm can notify you so that you can trigger an update on your UI. Let’s do that. Just before our second write where we add “John” and “Peter”, I’m going to add:


people.addNotificationBlock { _ in
    print("now update my UI")
}

I’m ignoring the parameter that it gets because we are just looking at how it’s going to work, and I just added a print statement inside. You can see that this block gets executed any time there’s an update to the underlying results. You should see in your console that now we have now update my UI printed in there because our second write triggered this block.

Not only will Realm always give you the latest data that you’re interested in, but it will also tell you when it’s the proper time to update your UI. If you power a collection view or table view, in here you will say table.reloadData. Or if you want to create animations for the elements that have been deleted or introduced and so forth, then you will use the parameter for the notification block to do those. We’re going to have a look at how to easily do that in the next videos.

Conclusion

Now you have a basic idea of the live results and how to use the notification mechanism. In the next episodes, we’re going to have a look in more detail. Thanks, and I’ll see you again.

Resources

Next Up: Demo: Build a Reactive App Using the Realm Mobile Platform

General link arrow white

Marin Todorov

Marin Todorov is an independent iOS consultant and publisher. He’s co-author on the book “RxSwift: Reactive programming with Swift” the author of “iOS Animations by Tutorials”. He’s part of Realm and raywenderlich.com. Besides crafting code, Marin also enjoys blogging, writing books, teaching, and speaking. He sometimes open sources his code. He walked the way to Santiago.