Last active
November 28, 2022 06:12
-
-
Save samsonjs/ee6f69546ec62aa6bf8d5b0fc433959d to your computer and use it in GitHub Desktop.
Slightly better type-safe notifications for Apple platforms
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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