Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Domain Events v1.1 -- without event name enum
import Foundation
public typealias UserInfo = [NSObject : AnyObject]
public protocol DomainEvent {
class var eventName: String { get }
init(userInfo: UserInfo)
func userInfo() -> UserInfo
}
public func notification<T: DomainEvent>(event: T) -> NSNotification {
return NSNotification(name: T.eventName, object: nil, userInfo: event.userInfo())
}
import Foundation
private struct DomainEventPublisherStatic {
static var singleton: DomainEventPublisher? = nil
static var onceToken: dispatch_once_t = 0
}
public class DomainEventPublisher {
public class var sharedInstance: DomainEventPublisher {
if DomainEventPublisherStatic.singleton == nil {
dispatch_once(&DomainEventPublisherStatic.onceToken) {
self.setSharedInstance(DomainEventPublisher())
}
}
return DomainEventPublisherStatic.singleton!
}
/// Reset the static `sharedInstance`, for example for testing
public class func resetSharedInstance() {
DomainEventPublisherStatic.singleton = nil
DomainEventPublisherStatic.onceToken = 0
}
public class func setSharedInstance(instance: DomainEventPublisher) {
DomainEventPublisherStatic.singleton = instance
}
let notificationCenter: NSNotificationCenter
public convenience init() {
self.init(notificationCenter: NSNotificationCenter.defaultCenter())
}
public init(notificationCenter: NSNotificationCenter) {
self.notificationCenter = notificationCenter
}
//MARK: -
//MARK: Event Publishing and Subscribing
public func publish<T: DomainEvent>(event: T) {
notificationCenter.postNotification(notification(event))
}
public func subscribe<T: DomainEvent>(eventKind: T.Type, usingBlock block: (T!) -> Void) -> DomainEventSubscription {
let mainQueue = NSOperationQueue.mainQueue()
return self.subscribe(eventKind, queue: mainQueue, usingBlock: block)
}
public func subscribe<T: DomainEvent>(eventKind: T.Type, queue: NSOperationQueue, usingBlock block: (T!) -> Void) -> DomainEventSubscription {
let eventName: String = T.eventName
let observer = notificationCenter.addObserverForName(eventName, object: nil, queue: queue) {
notification in
let userInfo = notification.userInfo!
let event: T = T(userInfo: userInfo)
block(event)
}
return DomainEventSubscription(observer: observer, eventPublisher: self)
}
public func unsubscribe(subscriber: AnyObject) {
notificationCenter.removeObserver(subscriber)
}
}
import Foundation
public class DomainEventSubscription {
let observer: NSObjectProtocol
let eventPublisher: DomainEventPublisher
public init(observer: NSObjectProtocol, eventPublisher: DomainEventPublisher) {
self.observer = observer
self.eventPublisher = eventPublisher
}
deinit {
eventPublisher.unsubscribe(observer)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.