-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit 73b2cc4
Showing
12 changed files
with
366 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
.DS_Store | ||
/.build | ||
/Packages | ||
/*.xcodeproj |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
The MIT License (MIT) | ||
Copyright (c) 2018 Imbue11235 | ||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
// swift-tools-version:4.0 | ||
// The swift-tools-version declares the minimum version of Swift required to build this package. | ||
|
||
import PackageDescription | ||
|
||
let package = Package( | ||
name: "EventHub", | ||
products: [ | ||
// Products define the executables and libraries produced by a package, and make them visible to other packages. | ||
.library( | ||
name: "EventHub", | ||
targets: ["EventHub"]), | ||
], | ||
dependencies: [ | ||
// Dependencies declare other packages that this package depends on. | ||
// .package(url: /* package url */, from: "1.0.0"), | ||
], | ||
targets: [ | ||
// Targets are the basic building blocks of a package. A target can define a module or a test suite. | ||
// Targets can depend on other targets in this package, and on products in packages which this package depends on. | ||
.target( | ||
name: "EventHub", | ||
dependencies: []), | ||
.testTarget( | ||
name: "EventHubTests", | ||
dependencies: ["EventHub"]), | ||
] | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
# Swift EventHub | ||
|
||
Simple implementation of an EventHub in Swift. | ||
Supports callbacks and listeners. | ||
|
||
## Examples | ||
|
||
### Callback | ||
|
||
```swift | ||
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 | ||
```swift | ||
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. 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 | ||
```swift | ||
let hub = EventHub(queue: .global()) | ||
``` | ||
2. Define events by making them comply to the `Event` protocol | ||
|
||
```swift | ||
struct MyEvent: Event {} | ||
``` | ||
|
||
3. Subscribe to the events either by callback or listener (see examples above) | ||
```swift | ||
hub.subscribe { (event: MyEvent) in | ||
// Do something with the event | ||
} | ||
``` | ||
|
||
4. Trigger events by calling the method `.trigger(event: Event)` | ||
```swift | ||
hub.trigger(MyEvent()) | ||
``` | ||
|
||
5. The events triggered are distributed to all listeners attached to the hub, listening for that specific event. | ||
|
||
6. To unsubscribe, the returned UUID from the `.subscribe` method, can be used | ||
```swift | ||
let subscription = hub.subscribe { // ... } | ||
hub.unsubscribe(subscription) | ||
``` | ||
|
||
## Requirements | ||
Swift 4.1 | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
public protocol Event {} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
extension EventHub { | ||
internal struct Subscriber { | ||
public let identifier: String | ||
public let handler: Any | ||
public let type: SubscriptionType | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
extension EventHub { | ||
internal enum SubscriptionType { | ||
case callback | ||
case listener | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
import Foundation | ||
|
||
final class EventHub { | ||
|
||
typealias Callback<T: Event> = (T) -> () | ||
|
||
private let queue: DispatchQueue | ||
private var subscriptions: [Subscriber] | ||
|
||
init(queue: DispatchQueue) { | ||
self.queue = queue | ||
self.subscriptions = [Subscriber]() | ||
} | ||
|
||
public func subscribe<T: Event>(with callback: @escaping Callback<T>) -> String { | ||
return self.observe(with: callback, as: .callback) | ||
} | ||
|
||
public func subscribe<T: Event>(with listener: Listener<T>) -> String { | ||
return self.observe(with: listener, as: .listener) | ||
} | ||
|
||
public func unsubscribe(identifier: String) { | ||
self.subscriptions = self.subscriptions.filter { $0.identifier != identifier } | ||
} | ||
|
||
public func trigger<T: Event>(event: T) { | ||
self.subscriptions.forEach { subscriber in | ||
self.queue.async { | ||
self.notify(a: subscriber, of: event) | ||
} | ||
} | ||
} | ||
|
||
private func observe(with handler: Any, as type: SubscriptionType) -> String { | ||
let uuid: String = UUID().uuidString | ||
|
||
self.subscriptions.append(Subscriber(identifier: uuid, handler: handler, type: type)) | ||
|
||
return uuid | ||
} | ||
|
||
private func notify<T: Event>(a subscriber: Subscriber, of event: T) { | ||
if subscriber.type == .listener { | ||
guard let handler = subscriber.handler as? Listener<T> else { | ||
return | ||
} | ||
|
||
handler.handle(event: event) | ||
|
||
return | ||
} | ||
|
||
// If the subscriber handler is a callback, try to unwrap it as a callback | ||
guard let handler = subscriber.handler as? Callback<T> else { | ||
return | ||
} | ||
|
||
handler(event) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
open class Listener<T: Event> { | ||
public func handle(event: T) { | ||
fatalError("Subclasses must implement the handle method") | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,146 @@ | ||
import XCTest | ||
@testable import EventHub | ||
|
||
final class EventHubTests: XCTestCase { | ||
|
||
private var eventHub: EventHub = EventHub(queue: .global()) | ||
|
||
struct IncrementCounterEvent: Event { | ||
var incrementation: Int | ||
} | ||
|
||
struct DeductingCounterEvent: Event { | ||
var deduct: Int | ||
} | ||
|
||
class CounterWasIncrementedListener: Listener<IncrementCounterEvent> { | ||
|
||
private var callback: (IncrementCounterEvent) -> () | ||
|
||
init(callback: @escaping (IncrementCounterEvent) -> ()) { | ||
self.callback = callback | ||
} | ||
|
||
override func handle(event: EventHubTests.IncrementCounterEvent) { | ||
self.callback(event) | ||
} | ||
} | ||
|
||
override func setUp() { | ||
// Overwriting on each test, to clear it | ||
self.eventHub = EventHub(queue: .global()) | ||
} | ||
|
||
func testCallbackWasCalledAfterEventFire() { | ||
let expectation = self.expectation(description: "Should recieve event on trigger") | ||
|
||
var count: Int = 0 | ||
let incrementBy: Int = 5 | ||
var recievedIncrementation: Int = 0 | ||
|
||
let _ = eventHub.subscribe { (event: IncrementCounterEvent) in | ||
count += event.incrementation | ||
recievedIncrementation = event.incrementation | ||
|
||
expectation.fulfill() | ||
} | ||
|
||
eventHub.trigger(event: IncrementCounterEvent(incrementation: incrementBy)) | ||
|
||
waitForExpectations(timeout: 2, handler: nil) | ||
|
||
XCTAssertEqual(recievedIncrementation, incrementBy) | ||
XCTAssertEqual(count, incrementBy) | ||
} | ||
|
||
func testEventsWasDistributedToAllCallbacks() { | ||
var count: Int = 0 | ||
let incrementBy: Int = 20 | ||
let iterations: Int = 3 | ||
|
||
for i in 1...iterations { | ||
let expectation = self.expectation(description: "Can fire event to multiple callbacks - Iteration \(i)") | ||
|
||
let _ = eventHub.subscribe { (event: IncrementCounterEvent) in | ||
count += event.incrementation | ||
|
||
expectation.fulfill() | ||
} | ||
} | ||
|
||
eventHub.trigger(event: IncrementCounterEvent(incrementation: incrementBy)) | ||
|
||
waitForExpectations(timeout: 2, handler: nil) | ||
|
||
XCTAssertEqual(count, incrementBy * iterations) | ||
} | ||
|
||
func testMultipleTypesOfEvents() { | ||
var count: Int = 0 | ||
|
||
let incrementBy: Int = 20 | ||
let incrementEvent = IncrementCounterEvent(incrementation: incrementBy) | ||
var recievedIncrementation: Int = 0 | ||
let incrementExpectation = self.expectation(description: "Should recieve IncrementEvent") | ||
|
||
let deductBy: Int = -10 | ||
let deductEvent = DeductingCounterEvent(deduct: deductBy) | ||
var recievedDeductation: Int = 0 | ||
let deductExpectation = self.expectation(description: "Should recieve DeductingEvent") | ||
|
||
let _ = eventHub.subscribe { (event: IncrementCounterEvent) in | ||
recievedIncrementation = event.incrementation | ||
count += event.incrementation | ||
|
||
incrementExpectation.fulfill() | ||
} | ||
|
||
let _ = eventHub.subscribe { (event: DeductingCounterEvent) in | ||
recievedDeductation = event.deduct | ||
count += event.deduct | ||
|
||
deductExpectation.fulfill() | ||
} | ||
|
||
eventHub.trigger(event: incrementEvent) | ||
eventHub.trigger(event: deductEvent) | ||
|
||
waitForExpectations(timeout: 2, handler: nil) | ||
|
||
XCTAssertEqual(count, incrementBy + deductBy) | ||
XCTAssertEqual(recievedIncrementation, incrementBy) | ||
XCTAssertEqual(recievedDeductation, deductBy) | ||
} | ||
|
||
func testListenerWasCalledAfterEventFire() { | ||
let expectation = self.expectation(description: "Should recieve IncrementEvent in Listener") | ||
|
||
var count: Int = 0 | ||
let incrementBy: Int = 20 | ||
var recievedIncrementation: Int = 0 | ||
|
||
let listener: CounterWasIncrementedListener = CounterWasIncrementedListener { event in | ||
count += event.incrementation | ||
recievedIncrementation = event.incrementation | ||
|
||
expectation.fulfill() | ||
} | ||
|
||
let _ = eventHub.subscribe(with: listener) | ||
|
||
eventHub.trigger(event: IncrementCounterEvent(incrementation: incrementBy)) | ||
|
||
waitForExpectations(timeout: 2, handler: nil) | ||
|
||
XCTAssertEqual(recievedIncrementation, incrementBy) | ||
XCTAssertEqual(count, incrementBy) | ||
} | ||
|
||
|
||
static var allTests = [ | ||
("testCallbackWasCalledAfterEventFire", testCallbackWasCalledAfterEventFire), | ||
("testEventsWasDistributedToAllCallbacks", testEventsWasDistributedToAllCallbacks), | ||
("testMultipleTypesOfEvents", testMultipleTypesOfEvents), | ||
("testListenerWasCalledAfterEventFire", testListenerWasCalledAfterEventFire) | ||
] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
import XCTest | ||
|
||
#if !os(macOS) | ||
public func allTests() -> [XCTestCaseEntry] { | ||
return [ | ||
testCase(EventHubTests.allTests), | ||
] | ||
} | ||
#endif |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
import XCTest | ||
|
||
import EventHubTests | ||
|
||
var tests = [XCTestCaseEntry]() | ||
tests += EventHubTests.allTests() | ||
XCTMain(tests) |