realm-swift: Add addNotificationBlock(_:) to Object

Goals

Be notified when any of an Object’s properties changes value.

There are addNotificationBlock methods on Results and List, which makes reacting to value changes very easy. For observing changes to an Object you got to use KVO, which is somewhat clunky should you not use a 3rd party lib for it.

I think there is a valid use case for adding addNotificationBlock to Object - especially when you are having a view controller that shows the information contained in a single object. For example in a Master-Detail application when you select one item in the master view controller you would have the following screen show all the data of a realm object (should that be how the app works). Now while the user has this screen open reacting to changes of the represented object means to observe each of the properties of that object. (Or the object representing the data in a single table cell, etc.)

I can see a complication in the implementation, which is the case in which the object gets deleted while having an active notification block attached - I think in that case calling the notification block one last time before the object is released with a nil value would suffice to provide means for the app to react to that event.

Expected Results

A view controllers viewDidLoad might look like this to always show live data on screen:

let luvStock = realm.objects(Stock).filter("symbol='LUV'").first!
self.updateUIWithStock(luvStock)
token = luvStock.addNotificationBlock {[weak self]latestStock, error in
  guard let `self` = self else {return}
  if let latestStock = latestStock {
    self.updateUIWithStock(luvStock)
  } else {
    self.popViewControllerAnimated(true)
  }
}

The example will fetch one Stock object from Realm, the update the UI any time any of the values has been updated in the background from the network controller, and finally if for whatever reason the object gets deleted it will just pop back to the previous screen.

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 19
  • Comments: 17 (10 by maintainers)

Most upvoted comments

This has been added in Realm 2.4.0! Yippee! 😃

0.98.7 is out, so the API docs have been updated and include the doc discussion for Results.addNotificationBlock(_:).