React to Changes - .NET SDK
On this page
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.
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:
- Realm notifications whenever a specific Realm commits a write transaction.
- Collection notifications whenever any Realm object in a collection changes, including inserts, updates, and deletes.
- Object notifications whenever a specific Realm object changes.
Subscribe to Changes
Generally, to observe changes, you create a notification handler for the Realm, collection, or object that you want to watch.
Register a Realm Change Listener
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.
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 ... };
Register a Collection Change Listener
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.
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.
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) => { if (error != null) { // Show error message return; } if (changes == null) { // This is the case when the notification is called // for the first time. // Populate tableview/listview with all the items // from `collection` return; } // Handle individual changes 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();
Every Realm collection implements INotifyCollectionChanged
, which allows
you to use a collection directly in data-binding scenarios.
Register an Object Change Listener
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.
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 += (sender, eventArgs) => { Debug.WriteLine("New value set for The King: " + eventArgs.PropertyName); }; }
Unregister a Change Listener
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 }