Navigation

Notifications

Note

Notifications only work when your realm regularly refreshes. In the Main or UI thread of your application, realm refreshes happen automatically. On background threads, you need to handle this yourself by either calling Realm.Refresh() or installing a SynchronizationContext on the thread before opening the realm. The third-party library Nito.AsyncEx.Context provides a SynchronizationContext implementation and a convenient API to install it.

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 an 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, to observe changes, you create a notification handler for the Realm, collection, or object that you want to watch.

Realm Notifications

You can register a notification handler on an entire Realm. Realm Database invokes 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.

// Observe realm notifications.
realm.RealmChanged += (sender, eventArgs) =>
{
    // sender is the realm that has changed.
    // eventArgs is reserved for future use.
    // ... update UI ...
}

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.

// Observe collection notifications. Retain the token to keep observing.
var token = _realm.All<Dog>().SubscribeForNotifications((sender, changes, error) =>
{
    foreach (var i in changes.DeletedIndices) {
        // ... handle deletions ...
    }

    foreach (var i in changes.InsertedIndices)
    {
        // ... handle insertions ...
    }

    foreach (var i in changes.NewModifiedIndices)
    {
        // ... handle modifications ...
    }
});

// Later, when you no longer wish to receive notifications
token.Dispose();

Note

Every Realm collection implements INotifyCollectionChanged, which allows you to use a collection directly in data-binding scenarios.

Object Notifications

You can register a notification handler on a specific object within a Realm. Realm Database notifies your handler when any of the object’s properties change.

The handler receives information about what fields have changed.

Example

The following code shows how to observe a specific object for changes.

var theKing = realm.All<Person>()
    .FirstOrDefault(p => p.Name == "Elvis Presley");

theKing.PropertyChanged += (s, e) =>
{
    Debug.WriteLine($"New value set for The King: {eventArgs.PropertyName}");
};

Unsubscribing from Events

When you no longer want to receive notifications on an event, you unsubscribe. The following code demonstrates this:

private IQueryable<Task> tasks;

public void LoadUI()
{
    tasks = realm.All<Task>();

    // Subscribe for notifications - since tasks is IQueryable<Task>, we're
    // using the AsRealmCollection extension method to cast it to IRealmCollection
    tasks.AsRealmCollection().CollectionChanged += OnTasksChanged;
}

public void UnloadUI()
{
    // Unsubscribe from notifications
    tasks.AsRealmCollection().CollectionChanged -= OnTasksChanged;
}

private void OnTasksChanged(object sender, NotifyCollectionChangedEventArgs args)
{
    // Do something with the notification information
}

Summary

  • Notifications allow you to watch for and react to changes on your objects, collections, and Realms.
  • When you know longer want to receive notifications, you unsubscript from the event.
  • 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.
←   Query Engine Threading  →