Created
January 15, 2018 23:48
-
-
Save alekseypotapov-dev/4ba6844e87b513ec565a5c54fa11d6cb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /// 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