Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save keith-kurak/32d4eddbc87f92a1e2fa5a8bfa81e88f to your computer and use it in GitHub Desktop.

Select an option

Save keith-kurak/32d4eddbc87f92a1e2fa5a8bfa81e88f to your computer and use it in GitHub Desktop.
Decoupled notification center subscription
//1) Notification center-specific implementation of UpdateObserving
class NotificationObserver: UpdateObserving {
var observer: NSObjectProtocol?
init(notificationObserver: NSObjectProtocol?) {
self.observer = notificationObserver
}
func unsubscribe() {
if(observer != nil) {
NotificationCenter.default.removeObserver(observer!)
}
}
}
//2) Repository method that subscribes to notifications
func observeRecordChanges(completionBlock: @escaping ([RecordModel]) -> ()) -> UpdateObserving {
let observer = NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "RecordsChangedNotification"), object: nil, queue: nil) { (notification) in
let records = //get records from somewhere
completionBlock(records)
}
return NotificationObserver(notificationObserver: observer)
}
//3) TableViewController.swift- doesn't this look familiar?
var records = [RecordModel]()
var recordObserver: UpdateObserving?
var repository = RepositoryWithNotificationCenterBasedSubscriptions()
func viewWillAppear(_ animated: Bool) {
self.recordObserver = self.repository.observeRecordChanges(completionBlock: { [unowned self] (records) in
DispatchQueue.main.async { [unowned self] in
self.records = records
self.tableView.reloadData()
}
}
// don't forget to clean up after yourself or things will get slow or buggy or both //
func viewWillDissappear(_ animated: Bool) {
self.recordObserver?.unsubscribe()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment