Skip to content

Instantly share code, notes, and snippets.

@samsonjs
Last active November 28, 2022 06:12
Show Gist options
  • Save samsonjs/ee6f69546ec62aa6bf8d5b0fc433959d to your computer and use it in GitHub Desktop.
Save samsonjs/ee6f69546ec62aa6bf8d5b0fc433959d to your computer and use it in GitHub Desktop.
Slightly better type-safe notifications for Apple platforms
import Combine
import Foundation
public protocol BetterNotification {}
private extension BetterNotification {
static var notificationName: Notification.Name {
Notification.Name(rawValue: "BetterNotification:\(Self.self)")
}
}
public extension Notification {
static func better<T: BetterNotification> (
_ betterNotification: T,
object: Any? = nil
) -> Notification {
Notification(name: T.notificationName, object: object, userInfo: [
"betterNotification": betterNotification,
])
}
}
public extension NotificationCenter {
func publisher<T: BetterNotification>(
for betterType: T.Type
) -> AnyPublisher<T, Never> {
publisher(for: betterType.notificationName )
.compactMap { $0.userInfo?["betterNotification"] as? T }
.eraseToAnyPublisher()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment