Latest 1.0.0
Homepage https://github.com/imbue11235/EventHub
License MIT
Platforms ios 10.0
Authors

Swift EventHub

Simple typesafe EventHub in Swift using callbacks/listeners defined by generic types.

Examples

Callback

struct CounterEvent: Event {
    let currentCount: Int
}

let eventHub = EventHub(queue: .global())
eventHub.subscribe { (event: CounterEvent)
    print(event.currentCount) // => 5
}

eventHub.trigger(CounterEvent(currentCount: 5))

Listener

struct SomeErrorEvent: Event {
    let message: String
    let code: Int 
}

class NotifyAdminListener: Listener<SomeErrorEvent> {
    override func handle(event: SomeErrorEvent) {
        print("Oh no! We got error (error.code) with the message '(error.message)'")
    }
}

let eventHub = EventHub(queue: .global())
eventHub.subscribe(NotifyAdminListener())
eventHub.trigger(SomeErrorEvent(message: "Fatal and dangerous error", code: 500))

Usage

  1. Import the library
    import SwiftEventHub
  2. Initialize the EventHub class on a DispatchQueue. Add the EventHub to a global scope (e.g. shared instance), for cross-events/listeners, or use it in an internal scope
    let hub = EventHub(queue: .global())
  3. Define events by making them comply to the Event protocol
struct MyEvent: Event {}
  1. Subscribe to the events either by callback or listener (see examples above)

    hub.subscribe { (event: MyEvent) in 
    // Do something with the event
    }
  2. Trigger events by calling the method .trigger(event: Event)

    hub.trigger(MyEvent())
  3. The events triggered are distributed to all listeners attached to the hub, listening for that specific event.

  4. To unsubscribe, the returned UUID from the .subscribe method, can be used
    let subscription = hub.subscribe { // ... }
    hub.unsubscribe(subscription)

Requirements

Swift 4.1

Installation

With CocoaPods:

pod 'SwiftEventHub'

Latest podspec

{
    "name": "SwiftEventHub",
    "version": "1.0.0",
    "summary": "EventHub vfor swift",
    "description": "Simple implementation of an EventHub in Swift. Supports callbacks and listeners.",
    "homepage": "https://github.com/imbue11235/EventHub",
    "license": {
        "type": "MIT",
        "file": "LICENSE"
    },
    "authors": {
        "imbue11235": "[email protected]"
    },
    "source": {
        "git": "https://github.com/imbue11235/EventHub.git",
        "tag": "1.0.0"
    },
    "platforms": {
        "ios": "10.0"
    },
    "source_files": "Sources/EventHub/*.swift"
}

Pin It on Pinterest

Share This