Skip to content

Instantly share code, notes, and snippets.

@ABridoux
Last active August 10, 2021 18:27
Show Gist options
  • Save ABridoux/e98290c4b530596db84e7e0a7a2702c7 to your computer and use it in GitHub Desktop.
Save ABridoux/e98290c4b530596db84e7e0a7a2702c7 to your computer and use it in GitHub Desktop.
A handy class to observe notifications with automatic unsubscribing and friendly syntax.
// 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)
}
}
@ABridoux
Copy link
Author

Explanations

📖 Read the article
⬇️ Get the playground

Some examples

extension NSNotification.Name {
    static let orderIsReady = Self(rawValue: "orderIsReady")
}

struct Cook {
    var center = NotificationCenter.default

    func notifyOrderReady() {
        center.post(.orderIsReady)
    }
}

final class Client {
    var observer: NotificationObserver?

    func startObserving() {
        observer = NotificationObserver(for: .orderIsReady) { [weak self] _ in self?.orderIsReady() }
    }

    func orderIsReady() {
        print("😋")
    }
}

// MARK: Test

let cook = Cook()
var client: Client? = Client()
client?.startObserving()
cook.notifyOrderReady() // print 😋

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment