d
This commit is contained in:
55
src/Bus.swift
Normal file
55
src/Bus.swift
Normal 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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user