本框架旨在重新思考 Apple 的 NotificationCenter,使其更具类型安全性,并消除 userInfo 字典中所需值存在的不确定性。它还可以用于处理 NSNotification.Name 订阅,性能优于 NSNotificationCenter。
假设您已经拥有(或至少知道如何创建)类似 DisposeBag 的系统,用于保持观察活跃。(当观察者令牌被释放时,观察会被清理)
// SampleNotification.swift
import TypedNotificationCenter
enum SampleNotification: TypedNotification {
struct Payload {
let type = "test"
}
typealias Sender = MyCustomView
}
// OtherFile.swift
// Observe a notification and execute a block with the sender and the payload
var observations = [TypedNotificationObservation]()
observations.append(TypedNotificationCenter.default.observe(SampleNotification.self, object: nil, block: { (sender, payload) in
print(sender, payload)
}))
// Post a notification
TypedNotificationCenter.default.post(SampleNotification.self, sender: self, payload: SampleNotification.Payload())
// Stop observing the notification, this is also called when the observation object deinitializes
observation?.invalidate()
enum KeyboardWillShowNotification: BridgedNotification {
public static var notificationName: Notification.Name = UIResponder.keyboardWillShowNotification
public typealias Sender = NSNull
public typealias Payload = KeyboardNotificationPayload
}
var observations = [TypedNotificationObservation]()
observations.append(TypedNotificationCenter.default.observe(NSLocale.currentLocaleDidChangeNotification, object: nil, queue: NSOperationQueue.mainQueue()) { notification in
print("The user's locale changed to: \(NSLocale.currentLocale().localeIdentifier)")
})