Проверка шаблона шины для iOS
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Bus.swift 1.7KB

11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
10 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import Combine
  2. import Foundation
  3. public enum Bus {
  4. private static let e = PassthroughSubject<(key: String, value: Any), Never>()
  5. public static var events: AnyPublisher<(key: String, value: Any), Never> {
  6. e.eraseToAnyPublisher()
  7. }
  8. }
  9. public extension Bus {
  10. /// Асинхронно обрабатываем входящие события из шины.
  11. static func receiveAsync<T>(
  12. _ keys: Set<String>,
  13. _ handler: @escaping ((String, T) -> Void),
  14. _ subscriptions: inout [AnyCancellable]
  15. ) {
  16. e
  17. .compactMap { convertKeyValue(keys, $0) }
  18. .receive(on: DispatchQueue.main)
  19. .sink { v in handler(v.0, v.1) }
  20. .store(in: &subscriptions)
  21. }
  22. /// Синхронно обрабатываем входящие события из шины.
  23. static func receiveSync<T>(
  24. _ keys: Set<String>,
  25. _ handler: @escaping ((String, T) -> Void),
  26. _ subscriptions: inout [AnyCancellable]
  27. ) {
  28. e
  29. .compactMap { convertKeyValue(keys, $0) }
  30. .sink { v in handler(v.0, v.1) }
  31. .store(in: &subscriptions)
  32. }
  33. /// Синхронно отправляем события из узла в шину.
  34. ///
  35. /// Для асинхронной отправки достаточно добавить оператор `receive(on:)`
  36. /// в цепочке параметра `node`
  37. static func sendSync<T>(
  38. _ key: String,
  39. _ node: AnyPublisher<T, Never>,
  40. _ subscriptions: inout [AnyCancellable]
  41. ) {
  42. node
  43. .sink { v in e.send((key, v)) }
  44. .store(in: &subscriptions)
  45. }
  46. /// Единоразово синхронно отправляем событие в шину.
  47. static func send(_ key: String, _ value: Any) {
  48. e.send((key, value))
  49. }
  50. }