swift-event-broadcasting

macOS (latest), Swift 5.8 workflow badge Ubuntu (latest), Swift 5.8 workflow badge

swift-event-broadcasting 是一个用于创建和观察事件的库。它在功能上类似于 Node.js 中的 events 模块。

在这里,EventBroadcaster 相当于 Node.js 的 EventEmitter,而事件订阅者则相当于事件处理程序。

特性

快速开始

创建一个事件广播器

继承 EventBroadcaster 或实现 EventBroadcasting 协议

import Events

class GPSService: EventBroadcaster {
}

class GPSServiceAlternate: EventBroadcasting {
  private let broadcaster: EventBroadcaster = EventBroadcaster()
  
  func subscribe(...) { broadcaster.subscribe(...) }
  ...
  func broadcast(...) { broadcaster.broadcast(...) }
}

订阅一个事件广播器

使用事件类型、作为闭包的事件处理程序以及可选的关联的 AnyHashable 进行订阅。

如果没有 AnyHashable,将返回一个 SubscriberId。如果您打算取消订阅(移除)事件处理程序,则应存储订阅者 ID 以便稍后调用 unsubscribe()

let gpsService = GPSService()

// Subscribe
let subscriberId = gpsService.subscribe(to: "locationUpdate") {
  print("location updated")
}

// Broadcast
gpsService.broadcast(Event(eventType: "locationUpdate"))
// prints "location updated"

// Unsubscribe
gpsService.unsubscribe(id: subscriberId, from: "locationUpdate")

如果有 AnyHashable,则不会返回订阅者 ID。要取消订阅,请传递相同的 AnyHashable

let gpsService = GPSService()
let someHashable: AnyHashable = ...

// Subscribe
gpsService.subscribe(someHashable, to: "locationUpdate") {
  print("location updated")
}

// Broadcast
gpsService.broadcast(Event(eventType: "locationUpdate"))
// prints "location updated"

// Unsubscribe
gpsService.unsubscribe(subscriber: someHashable, from: "locationUpdate")