EventStream
An insanely-useful, protocol-oriented event bus written in Swift.
Why not NotificationCenter?
NotificationCenter doesn't suck. It was just written in Objective-C. In Swift, we can do better.
EventStream Advantages
- Its cleanup is based on reference semantics. There is no concept of
removeObserver(). - Every observer receives every event. It's up to the observer to determine which events are worth acting upon.
- Events are classes and are therefore type-safe. See Usage below for an example.
Usage
Adding an observer
class MyObservingViewController: UIViewController, EventStreamObserver {
override func viewDidLoad() {
super.viewDidLoad()
EventStream.addObserver(self)
}
}
Defining an event type
class TextSubmittedEvent: StreamEvent {
let submittedText: String
init(_ text: String) {
submittedText = text
}
}
Sending an event
let newTextSubmittedEvent = TextSubmittedEvent("This is text I'm submitting")
EventStream.send(newTextSubmittedEvent)
Observing an event
extension class MyObservingViewController {
func observedStreamEvent(_ event: StreamEvent) {
if let textSubmittedEvent = event as? TextSubmittedEvent {
print("Received submitted text: \(textSubmittedEvent.submittedText)")
}
}
}
Sending an event on a specific DispatchQueue
EventStream.send(newDarkModeSettingChangedEvent, on: .main)
Installation
Drop EventStream.swift into your project. Done!
License
The MIT License (MIT)
Copyright © 2017-2018 Nicolas Cook Leon
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.