Last active
August 10, 2021 18:27
-
-
Save ABridoux/e98290c4b530596db84e7e0a7a2702c7 to your computer and use it in GitHub Desktop.
A handy class to observe notifications with automatic unsubscribing and friendly syntax.
This file contains 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
// Free to use | |
// Written by Alexis Bridoux - https://github.com/ABridoux | |
/// Observes a notification and executes the provided block upon reception | |
/// | |
/// Unregister the stored observer upon deinitialization | |
final class NotificationObserver { | |
var name: Notification.Name | |
var observer: NSObjectProtocol | |
var center = NotificationCenter.default | |
init(for name: Notification.Name, block: @escaping (Notification) -> Void) { | |
self.name = name | |
observer = center.addObserver(for: name, using: block) | |
} | |
deinit { | |
center.removeObserver(observer, name: name) | |
} | |
} | |
// MARK: - Array | |
extension Array where Element == NotificationObserver { | |
mutating func append(name: NSNotification.Name, using block: @escaping (Notification) -> Void) { | |
append(NotificationObserver(for: name, block: block)) | |
} | |
} | |
// MARK: - NotificationCenter extensions | |
extension NotificationCenter { | |
func post(_ notificationName: NSNotification.Name) { | |
post(name: notificationName, object: nil) | |
} | |
func addObserver( | |
for notificationName: NSNotification.Name, | |
using block: @escaping (Notification) -> Void) | |
-> NSObjectProtocol { | |
addObserver(forName: notificationName, object: nil, queue: nil, using: block) | |
} | |
func removeObserver(_ observer: NSObjectProtocol, name: NSNotification.Name) { | |
removeObserver(observer, name: name, object: nil) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Explanations
📖 Read the article
⬇️ Get the playground
Some examples