Navigation

Notifications

Overview

Any modern app should be able to react when data changes, regardless of where that change originated. When a user adds a new item to a list, you may want to update the UI, show a notification, or log a message. When someone updates that item, you may want to change its visual state or fire off a network request. Finally, when someone deletes the item, you probably want to remove it from the UI. Realm’s notification system allows you to watch for and react to changes in your data, independent of the writes that caused the changes.

Realm emits three kinds of notifications:

Subscribe to Changes

Generally, this is how you observe a Realm, collection, or object:

  1. Create a notification handler for the Realm, collection, or object notification.
  2. Add the notification handler to the Realm, collection, or object that you want to observe.
  3. Receive a notification token from the call to add the handler. Retain this token as long as you want to observe.
  4. When you are done observing, invalidate the token.

Realm Notifications

You can register a notification handler on an entire Realm. Realm Database calls the notification handler whenever any write transaction involving that Realm is committed. The handler receives no information about the change.

This is useful when you want to know that there has been a change but do not care to know specifically what changed. For example, proof of concept apps often use this notification type and simply refresh the entire UI when anything changes. As the app becomes more sophisticated and performance-sensitive, the app developers shift to more granular notifications.

Example

Suppose you are writing a real-time collaborative app. To give the sense that your app is buzzing with collaborative activity, you want to have an indicator that lights up when any change is made. In that case, a realm notification handler would be a great way to drive the code that controls the indicator.

function updateUI() {
  // ... handle update to the UI ...
}

// Observe realm notifications.
realm.addListener('change', updateUI);

// ..later remove the listener
realm.removeListener('change', updateUI);

// ..or unregister all listeners
realm.removeAllListeners();

Collection Notifications

You can register a notification handler on a specific collection within a Realm. The handler receives a description of changes since the last notification. Specifically, this description consists of three lists of indices:

  • The indices of the objects that were deleted.
  • The indices of the objects that were inserted.
  • The indices of the objects that were modified.

Order Matters

In collection notification handlers, always apply changes in the following order: deletions, insertions, then modifications. Handling insertions before deletions may result in unexpected behavior.

Realm Database emits an initial notification after retrieving the collection. After that, Realm Database delivers collection notifications asynchronously whenever a write transaction adds, changes, or removes objects in the collection.

Unlike Realm notifications, collection notifications contain detailed information about the change. This enables sophisticated and selective reactions to changes. Collection notifications provide all the information needed to manage a list or other view that represents the collection in the UI.

Example

The following code shows how to observe a collection for changes in order to update the UI.

const dogs = realm.objects('Dog');

// Define the collection notification listener
function listener(dogs, changes) {

  // Update UI in response to deleted objects
  changes.deletions.forEach((index) => {
    // Deleted objects cannot be accessed directly,
    // but we can update a UI list, etc. knowing the index.
  });

  // Update UI in response to inserted objects
  changes.insertions.forEach((index) => {
    let insertedDog = dogs[index];
    // ...
  });

  // Update UI in response to modified objects
  changes.modifications.forEach((index) => {
    let modifiedDog = dogs[index];
    // ...
  });
}

// Observe collection notifications.
dogs.addListener(listener);

// Unregister all listeners
realm.removeAllListeners();

// OR Unregister this listener
dogs.removeListener(listener);

Object Notifications

You can register a notification handler on a specific object within a Realm. Realm Database notifies your handler:

  • When the object is deleted.
  • When any of the object’s properties change.

The handler receives information about what fields changed and whether the object was deleted.

Example

The following code shows how to open a default realm, create a new instance of a class, and observe that instance for changes.

async function example() {
  // Open the default realm.
  const realm = await Realm.open();

  let dog;

  // Create an entry.
  realm.write(() => {
    dog = realm.create('Dog', {name: 'Max'})
  });

  // Observe object notifications.
  dog.addListener((obj, changes) => {
    // obj === dog
    console.log(`object is deleted? ${changes.deleted}`);
    console.log(`${changes.changedProperties.length} properties have been changed:`);
    changes.changedProperties.forEach((prop) => {
      console.log(` ${prop}`);
    });
  });

  // Later, update the dog to trigger the notification.
  realm.write(() => {
    dog.name = 'Wolfie'
  });
}

Summary

  • Notifications allow you to watch for and react to changes on your objects, collections, and Realms.
  • When you add a notification handler to an object, collection, or Realm that you wish to observe, you receive a token. Retain this token as long as you wish to keep observing.
  • Realm Database has three notification types: Realm, collection, and object notifications. Realm notifications only tell you that something changed, while collection and object notifications allow for more granular observation.
←   Collections Realms  →