Проверка шаблона шины для iOS
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

93 строки
2.4KB

  1. import Combine
  2. import Foundation
  3. public enum Bus { }
  4. extension Bus {
  5. final class Service {
  6. static let singleton = Service()
  7. let events = PassthroughSubject<(key: String, value: Any), Never>()
  8. var subscriptions = Set<AnyCancellable>()
  9. func send(_ key: String, _ value: Any) {
  10. /**/print("ИГР BusS.send key/value: '\(key)'/'\(value)'")
  11. events.send((key, value))
  12. }
  13. }
  14. }
  15. public extension Bus {
  16. static func receiveAsync<T>(
  17. _ subscriptions: inout Set<AnyCancellable>,
  18. _ keys: Set<String>,
  19. _ handler: @escaping ((String, T) -> Void)
  20. ) {
  21. Service.singleton.events
  22. .compactMap { convertKeyValue(keys, $0) }
  23. .receive(on: DispatchQueue.main)
  24. .sink { v in handler(v.0, v.1) }
  25. .store(in: &subscriptions)
  26. }
  27. static func receiveSync<T>(
  28. _ subscriptions: inout Set<AnyCancellable>,
  29. _ keys: Set<String>,
  30. _ handler: @escaping ((String, T) -> Void)
  31. ) {
  32. Service.singleton.events
  33. .compactMap { convertKeyValue(keys, $0) }
  34. .sink { v in handler(v.0, v.1) }
  35. .store(in: &subscriptions)
  36. }
  37. static func sendAsync<T>(
  38. _ subscriptions: inout Set<AnyCancellable>,
  39. _ key: String,
  40. _ node: AnyPublisher<T, Never>
  41. ) {
  42. node
  43. .receive(on: DispatchQueue.main)
  44. .sink { v in Service.singleton.send(key, v) }
  45. .store(in: &subscriptions)
  46. }
  47. static func sendSync<T>(
  48. _ subscriptions: inout Set<AnyCancellable>,
  49. _ key: String,
  50. _ node: AnyPublisher<T, Never>
  51. ) {
  52. node
  53. .sink { v in Service.singleton.send(key, v) }
  54. .store(in: &subscriptions)
  55. }
  56. static func send(_ key: String, _ value: Any) {
  57. Service.singleton.send(key, value)
  58. }
  59. }
  60. public extension Bus {
  61. static func processSync<Src, Dst>(
  62. _ subscriptions: inout Set<AnyCancellable>,
  63. _ handler: @escaping ((Src) -> Dst?),
  64. _ keyIn: String,
  65. _ keyOut: String
  66. ) {
  67. Service.singleton.events
  68. .compactMap { processKeyValue($0, keyIn, handler) }
  69. .sink { vOut in Service.singleton.send(keyOut, vOut) }
  70. .store(in: &subscriptions)
  71. }
  72. static func processSyncG<Src, Dst>(
  73. _ handler: @escaping ((Src) -> Dst?),
  74. _ keyIn: String,
  75. _ keyOut: String
  76. ) {
  77. Service.singleton.events
  78. .compactMap { processKeyValue($0, keyIn, handler) }
  79. .sink { vOut in Service.singleton.send(keyOut, vOut) }
  80. .store(in: &Service.singleton.subscriptions)
  81. }
  82. }