This library attaches type-information to NotificationCenter
.
You can post and observe notifications in a type-safe manner.
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
}
Define a notification and how to encode/decode the userInfo in TypedNotificationDefinition
.
extension TypedNotificationDefinition {
static var userNameWillUpdate: TypedNotificationDefinition<String, User> {
.init(name: "userWillUpdate") { newName in
["newName": newName]
} decode: { userInfo in
userInfo?["newName"] as? String ?? ""
}
}
}
And then, you can post/observe the notifications in type safe manner.
// [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
// ...
}
You can use @Notification
macro, if @UserInforRepresentable
macro is attached to your type.
extension TypedNotificationDefinition {
@Notification
static var userNameUpdate: TypedNotificationDefinition<UserNameUpdateNotificationStorage, User>
}
@UserInfoRepresentable
struct UserNameUpdateNotificationStorage {
let oldName: String
let newName: String
}
This repository contains frequent system notifications.
- UIKit
- Core Data
Your PR adding new notifications is appreciated. Feel free to make a new PR.