Notify.swift (1072B)
1 // 2 // Notify.swift 3 // damus 4 // 5 // Created by William Casarin on 2023-07-30. 6 // 7 8 import Foundation 9 import Combine 10 11 protocol Notify { 12 associatedtype Payload 13 static var name: Notification.Name { get } 14 var payload: Payload { get } 15 } 16 17 extension Notify { 18 static var name: Notification.Name { 19 Notification.Name("\(Self.self)") 20 } 21 } 22 23 // needed because static dispatch off protocol extensions doesn't work so well 24 struct Notifications<T: Notify> { 25 let notify: T 26 27 init(_ notify: T) { 28 self.notify = notify 29 } 30 } 31 32 struct NotifyHandler<T> { } 33 34 func notify<T: Notify>(_ notify: Notifications<T>) { 35 let notify = notify.notify 36 NotificationCenter.default.post(name: T.name, object: notify.payload) 37 } 38 39 func handle_notify<T: Notify>(_ handler: NotifyHandler<T>) -> AnyPublisher<T.Payload, Never> { 40 return NotificationCenter.default.publisher(for: T.name) 41 //.compactMap { notification in notification.object as? T.Payload } 42 .map { notification in notification.object as! T.Payload } 43 .eraseToAnyPublisher() 44 }