---
title: "#231: Fine-Grained Notifications in Realm 🔮"
url: https://littlebitesofcocoa.com/231-fine-grained-notifications-in-realm
author: Jake Marsh
published: 2016-05-02
topics: ["Models","Libraries","Realm"]
description: "We first looked at Realm way back in Bite #49. It's a great data storage solution for our mobile apps. Today we'll start looking at some of the latest..."
---

# #231: Fine-Grained Notifications in Realm 🔮

By Jake Marsh, May 2, 2016. HTML: https://littlebitesofcocoa.com/231-fine-grained-notifications-in-realm

We first looked at [Realm](https://realm.io/) way back in [Bite #49](https://littlebitesofcocoa.com/49). It's a great data storage solution for our mobile apps. Today we'll start looking at some of the latest improvements in Realm and the new capabilities they offer. First up is <i>Fine-grained notifications</i>. Let's dive in:

[Realm](http://realm.io) has offered **notifications** of write operations for a while, they look like this:

``` swift
let token = realm.addNotificationBlock { notif, realm in
  // TODO: viewController.updateUI()
}
```

These are still around and work great, but it might help to know more about what changed. That's where the new [Collection Notifications](https://realm.io/docs/swift/latest/#collection-notifications) come in.

**Collection notifications** give us access the changes that just occurred at a fine-grained level, including the specific indices of insertions, deletions, etc

``` swift
let results = try! Realm().objects(Spaceship).sorted("name")
let token = results.addNotificationBlock { (changes: RealmCollectionChange) in
  // TODO: self.processChanges(changes)
}
```

`changes` here is an **enum** that looks like this:

``` swift
public enum RealmCollectionChange<T> {
  case Initial(T)
  case Update(T, deletions: [Int], insertions: [Int], modifications: [Int])
  case Error(NSError)
}
```

`.Update's` values can be easily mapped to **NSIndexPath** objects suitable for use in **table views** and **collection views**.

Here's a complete example showing all of this in action:

``` swift
class SpaceshipsViewController: UITableViewController {
  var notificationToken: NotificationToken? = nil

  override func viewDidLoad() {
    super.viewDidLoad()
    let realm = try! Realm()
    let results = realm.objects(Spaceships).filter("maxSpeed > 0")

    // Observe Results Notifications
    notificationToken = results.addNotificationBlock { [weak self] (changes: RealmCollectionChange) in
      guard let tableView = self?.tableView else { return }
      switch changes {
      case .Initial:
        // Results are now populated and can be accessed without blocking the UI
        tableView.reloadData()
        break
      case .Update(_, let deletions, let insertions, let modifications):
        // Query results have changed, so apply them to the UITableView
        tableView.beginUpdates()
        tableView.insertRowsAtIndexPaths(insertions.map { NSIndexPath(forRow: $0, inSection: 0) }, withRowAnimation: .Automatic)
        tableView.deleteRowsAtIndexPaths(deletions.map { NSIndexPath(forRow: $0, inSection: 0) }, withRowAnimation: .Automatic)
        tableView.reloadRowsAtIndexPaths(modifications.map { NSIndexPath(forRow: $0, inSection: 0) }, withRowAnimation: .Automatic)
        tableView.endUpdates()
        break
      case .Error(let error):
        // An error occurred while opening the Realm file on the background worker thread
        fatalError("\(error)")
        break
      }
    }
  }

  deinit {
    notificationToken?.stop()
  }
}
```

More info about _Realm_ can be found at [realm.io](http://realm.io)
