This commit is contained in:
Михаил Капелько
2023-12-13 19:19:53 +03:00
parent acaaf68d9f
commit 30efa129a8
5 changed files with 262 additions and 0 deletions

55
src/Bus.swift Normal file
View File

@@ -0,0 +1,55 @@
import Combine
import SwiftUI
public enum Bus { }
extension Bus {
public final class Service {
static private(set) weak var singleton: Service?
let broadcaster = PassthroughSubject<(key: String, value: Any), Never>()
deinit {
Self.singleton = nil
}
public init() {
Self.singleton = self
}
func send(_ key: String, _ value: Any) {
broadcaster.send((key, value))
}
}
}
public extension Bus {
static func receive<T>(
_ subscriptions: inout Set<AnyCancellable>,
_ keys: Set<String>,
_ handler: @escaping ((String, T) -> Void)
) {
Service.singleton?.broadcaster
.compactMap { v -> (String, T)? in
guard
keys.contains(v.key),
let value = v.value as? T
else {
return nil
}
return (v.key, value)
}
.sink { v in handler(v.0, v.1) }
.store(in: &subscriptions)
}
static func sendAsync<T: Equatable>(
_ subscriptions: inout Set<AnyCancellable>,
_ key: String,
_ node: AnyPublisher<T, Never>
) {
node
.receive(on: DispatchQueue.main)
.sink { v in Service.singleton?.send(key, v) }
.store(in: &subscriptions)
}
}