This file contains hidden or 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
public class Event<T> { | |
// Return false if the event handler should be removed, ie: if the class instance used in the event handler is no longer valid | |
// { [weak self] val in | |
// guard let strongSelf = self else { | |
// return false | |
// } | |
// strongSelf.doStuff(with: val) | |
// return true | |
// } | |
public typealias EventHandler = ((T) -> Bool) | |
public init() {} | |
public func notify(_ event: T) { | |
for (uuid, eventHandler) in uiEventHandlers { | |
DispatchQueue.main.async { [weak self] in | |
if eventHandler(event) == false { | |
self?.uiEventHandlers[uuid] = nil | |
} | |
} | |
} | |
for (uuid, eventHandler) in eventHandlers { | |
if eventHandler(event) == false { | |
eventHandlers[uuid] = nil | |
} | |
} | |
} | |
public func subscribe(uuid: UUID, eventHandler: @escaping EventHandler) { | |
eventHandlers[uuid] = eventHandler | |
} | |
public func uiSubscribe(uuid: UUID, eventHandler: @escaping EventHandler) { | |
uiEventHandlers[uuid] = eventHandler | |
} | |
public func uiUnsubscribe(uuid: UUID) { | |
uiEventHandlers[uuid] = nil | |
} | |
public func unsubscribe(uuid: UUID) { | |
eventHandlers[uuid] = nil | |
} | |
private var eventHandlers: [UUID: EventHandler] = [:] | |
private var uiEventHandlers: [UUID: EventHandler] = [:] | |
} |
Use the uiSubscribe and uiUnsubscribe to have the Event class automatically run the event handler on the main DispatchQueue (for GUI related stuff). Here is an example of how to use them:
This file contains hidden or 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
class EventProducer { | |
var value: Int = 0 { | |
didSet { | |
valueEvent.notify(value) | |
} | |
} | |
let valueEvent = Event<Int>() | |
} | |
class EventConsumer { | |
init(producer: EventProducer) { | |
producersValue = producer.value | |
producer.valueEvent.subscribe(uuid: uuid) { [weak self] value in | |
guard let strongSelf = self else { | |
return false | |
} | |
print("Value changed: \(value)") | |
strongSelf.producersValue = value | |
return true | |
} | |
} | |
private var producersValue: Int | |
private let uuid = UUID() | |
} | |
let producer = EventProducer() | |
let consumer = EventConsumer(producer: producer) | |
producer.value = 5 |