Filter Realm Notifications in Your iOS App with KeyPaths
Rate this tutorial
By default, notifications return changes for all insertions, modifications, and deletions. Suppose that I have a schema that looks like the one below.
If I observe a
Results<Company>object and the name of one of the companies in the results changes, the notification block would fire and my UI would update:
That’s quite straightforward for non-collection properties. But what about other types, like lists?
Naturally, the block I passed into .
observewill execute each time an
Orderis added or removed. But the block also executes each time a property on the
Orderlist is edited. The same goes for those properties’ collections too (and so on!). Even though I’m observing “just” a collection of
Companyobjects, I’ll receive change notifications for properties on a half-dozen other collections.
This isn’t necessarily an issue for most cases. Small object graphs, or “siloed” objects, that don’t feature many relationships might not experience unneeded notifications at all. But for complex webs of objects, where several layers of children objects exist, an app developer may benefit from a major performance enhancement and added control from KeyPath filtering.
.observecomes with an optional
.observefunction will only notify on the field or fields specified in the
keyPathsparameter. Other fields are ignored unless explicitly passed into the parameter.
This allows the app developer to tailor which relationship paths are observed. This reduces computing cost and grants finer control over when the notification fires.
Our modified code might look like this:
.observecan alternatively take a
If we applied the above snippets to our previous example, we’d only receive notifications for this portion of the schema:
The notification process is no longer traversing an entire tree of relationships each time a modification is made. Within a complex tree of related objects, the change-notification checker will now traverse only the relevant paths. This saves huge amounts of work.
In a large database, this can be a serious performance boost! The end-user can spend less time with a spinner and more time using your application.
.observehas a new optional
- The app developer has more granular control over when notifications are fired.
- This can greatly improve notification performance for large databases and complex object graphs.
News & Announcements
Introducing Flexible Sync (Preview) – The Next Iteration of Realm Sync
Oct 19, 2022