typed-notifications (类型化通知)
这个库为 NotificationCenter 添加了类型信息。
你可以以类型安全的方式发布和观察通知。
TypedNotificationCenter.default
.publisher(for: .userNameUpdate, object: user)
.sink { notification in
// Notifications can be received in a type safe manner.
let storage: UserNameUpdateNotificationStorage = notification.storage
let user: User? = notification.object
// ...
}
extension TypedNotificationDefinition {
@Notification
static var userNameUpdate: TypedNotificationDefinition<UserNameUpdateNotificationStorage, User>
}
@UserInfoRepresentable
struct UserNameUpdateNotificationStorage {
let oldName: String
let newName: String
}
在 TypedNotificationDefinition
中定义一个通知以及如何编码/解码 userInfo。
extension TypedNotificationDefinition {
static var userNameWillUpdate: TypedNotificationDefinition<String, User> {
.init(name: "userWillUpdate") { newName in
["newName": newName]
} decode: { userInfo in
userInfo?["newName"] as? String ?? ""
}
}
}
然后,你可以以类型安全的方式发布/观察通知。
// [Post]
// Notifications can be posted in a type safe manner.
let newName: String = ...
let user: User = ...
TypedNotificationCenter.default.post(.userNameWillUpdate, storage: newName, object: user)
// [Observation]
TypedNotificationCenter.default.publisher(for: .userNameWillUpdate, object: user)
.sink { notification in
// Notifications can be received in a type safe manner.
let newName = notification.storage
let user: User? = notification.object
// ...
}
如果 @UserInforRepresentable
宏附加到你的类型,你可以使用 @Notification
宏。
extension TypedNotificationDefinition {
@Notification
static var userNameUpdate: TypedNotificationDefinition<UserNameUpdateNotificationStorage, User>
}
@UserInfoRepresentable
struct UserNameUpdateNotificationStorage {
let oldName: String
let newName: String
}
这个仓库包含常用的系统通知。
欢迎提交 PR 添加新的通知。请随意创建新的 PR。