swift-event-broadcasting

0.0.2

Event handling implementation for Swift
antonsynd/swift-event-broadcasting

What's New

Swift Event Broadcasting 0.0.2

2023-07-12T02:26:25Z

Opens the Event and EventBroadcaster class for subclassing.

swift-event-broadcasting

macOS (latest), Swift 5.8 workflow badge

Ubuntu (latest), Swift 5.8 workflow badge

Event handling implementation for Swift.

Basics

An event broadcaster is an object that extends EventBroadcaster or implements the EventBroadcasting protocol. It broadcasts events to subscribers via broadcast().

Subscribers are event handlers (callback functions). They are subscribed to event broadcasters via the subscribe() method on the event broadcaster.

When an event is broadcasted via an event broadcaster's broadcast() method, all event handlers for that event's type are invoked synchronously in the order in which they were subscribed in a separate execution queue (which doesn't block the main thread).

How to

Create an event broadcaster

Extend EventBroadcaster or implement the EventBroadcasting protocol:

import Events

class GPSService: EventBroadcaster {
}

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

Subscribe to an event broadcaster

Subscribe with an event type, the event handler as a closure, and optionally an associated AnyHashable.

Without an AnyHashable, a SubscriberId will be returned. If you intend on unsubscribing (removing) the event handler, then you should store the subscriber id to call unsubscribe() later.

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")

With an AnyHashable, no subscriber id will be returned. To unsubscribe, pass the same 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")

Description

  • Swift Tools 5.8.0
View More Packages from this Author

Dependencies

Last updated: Sun Oct 20 2024 12:27:06 GMT-0900 (Hawaii-Aleutian Daylight Time)