Reputation: 14060
Swift 3.1, Xcode 8.3.3
I have a Realm notification that gets set up in a View Controller in my app, and after my app launches, it fires 4 times in a row.
let realm = try! Realm()
notificationToken = realm.addNotificationBlock { notification, realm in
print("notif: \(notification)") <-- Logs 4 times in a split second
self.refreshData()
}
Since the refreshData()
method is what refreshes my UI (which contains a graph that gets drawn), I see a jitter/flicker as each refresh hits.
Is there a way to aggregate those notifications into a single one so I only get a single UI refresh?
Upvotes: 0
Views: 577
Reputation: 54706
If you set up a notification block on a Realm instance, you will receive a notification per write transaction. To "aggregate" individual notifications into a single one, you need to merge your separate write transactions into a single one.
For example this piece of code fires two notifications:
try! realm.write {
realm.add(Person(value: ["name":"John"]))
realm.add(Person(value: ["name":"Chris"]))
}
try! realm.write {
realm.add(Person(value: ["name":"James"]))
}
While this code fires only one:
try! realm.write {
realm.add(Person(value: ["name":"John"]))
realm.add(Person(value: ["name":"Chris"]))
realm.add(Person(value: ["name":"James"]))
}
Clarification based on @bdash's comment, even though the docs state that "Every time a write transaction involving that Realm is committed, no matter which thread or process the write transaction took place on, the notification handler will be fired...", in reality notifications from several write transactions might be merged into a single one based on the time it takes for the notification code to process the write transactions.
Upvotes: 2