类型安全的通知中心

Code coverage codebeat badge GitHub release MIT Licence

Platforms Carthage Compatible Swift Package Manager Compatible CocoaPods Compatible

本框架旨在重新思考 Apple 的 NotificationCenter,使其更具类型安全性,并消除 userInfo 字典中所需值存在的不确定性。它还可以用于处理 NSNotification.Name 订阅,性能优于 NSNotificationCenter。

假设您已经拥有(或至少知道如何创建)类似 DisposeBag 的系统,用于保持观察活跃。(当观察者令牌被释放时,观察会被清理)

示例用法

类型安全 API

// 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
}

1:1 直接替换,用于现有的 NSNotificationCenter 用法

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)")
})