Skip to content

Instantly share code, notes, and snippets.

@alekseypotapov-dev
Created January 15, 2018 23:48
Show Gist options
  • Select an option

  • Save alekseypotapov-dev/4ba6844e87b513ec565a5c54fa11d6cb to your computer and use it in GitHub Desktop.

Select an option

Save alekseypotapov-dev/4ba6844e87b513ec565a5c54fa11d6cb to your computer and use it in GitHub Desktop.
/// Wraps the observer token received from
/// NotificationCenter.addObserver(forName:object:queue:using:)
/// and unregisters it in deinit.
final class NotificationToken: NSObject {
let notificationCenter: NotificationCenter
let token: Any
init(notificationCenter: NotificationCenter = .default, token: Any) {
self.notificationCenter = notificationCenter
self.token = token
}
deinit {
notificationCenter.removeObserver(token)
}
}
extension NotificationCenter {
/// Convenience wrapper for addObserver(forName:object:queue:using:)
/// that returns our custom NotificationToken.
func observe(name: NSNotification.Name?, object obj: Any?,
queue: OperationQueue?, using block: @escaping (Notification) -> ())
-> NotificationToken
{
let token = addObserver(forName: name, object: obj, queue: queue, using: block)
return NotificationToken(notificationCenter: self, token: token)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment