|
- import Combine
- import Foundation
-
- public enum Bus { }
-
- extension Bus {
- final class Service {
- static let singleton = Service()
- let events = PassthroughSubject<(key: String, value: Any), Never>()
- var subscriptions = Set<AnyCancellable>()
-
- func send(_ key: String, _ value: Any) {
- /**/print("ИГР BusS.send key/value: '\(key)'/'\(value)'")
- events.send((key, value))
- }
- }
- }
-
- public extension Bus {
- static func receiveAsync<T>(
- _ subscriptions: inout Set<AnyCancellable>,
- _ keys: Set<String>,
- _ handler: @escaping ((String, T) -> Void)
- ) {
- Service.singleton.events
- .compactMap { convertKeyValue(keys, $0) }
- .receive(on: DispatchQueue.main)
- .sink { v in handler(v.0, v.1) }
- .store(in: &subscriptions)
- }
-
- static func receiveSync<T>(
- _ subscriptions: inout Set<AnyCancellable>,
- _ keys: Set<String>,
- _ handler: @escaping ((String, T) -> Void)
- ) {
- Service.singleton.events
- .compactMap { convertKeyValue(keys, $0) }
- .sink { v in handler(v.0, v.1) }
- .store(in: &subscriptions)
- }
-
- static func sendAsync<T>(
- _ 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)
- }
-
- static func sendSync<T>(
- _ subscriptions: inout Set<AnyCancellable>,
- _ key: String,
- _ node: AnyPublisher<T, Never>
- ) {
- node
- .sink { v in Service.singleton.send(key, v) }
- .store(in: &subscriptions)
- }
-
- static func send(_ key: String, _ value: Any) {
- Service.singleton.send(key, value)
- }
- }
-
- public extension Bus {
- static func processSync<Src, Dst>(
- _ subscriptions: inout Set<AnyCancellable>,
- _ handler: @escaping ((Src) -> Dst?),
- _ keyIn: String,
- _ keyOut: String
- ) {
- Service.singleton.events
- .compactMap { processKeyValue($0, keyIn, handler) }
- .sink { vOut in Service.singleton.send(keyOut, vOut) }
- .store(in: &subscriptions)
- }
-
- static func processSyncG<Src, Dst>(
- _ handler: @escaping ((Src) -> Dst?),
- _ keyIn: String,
- _ keyOut: String
- ) {
- Service.singleton.events
- .compactMap { processKeyValue($0, keyIn, handler) }
- .sink { vOut in Service.singleton.send(keyOut, vOut) }
- .store(in: &Service.singleton.subscriptions)
- }
- }
|