A replacement for NSNotificationCenter#addObserver and NSObject#addObserver that is type-safe and not verbose.
import EmitterKit // A generic event emitter (but type-safe)! var event = Event<T>() // Any emitted data must be the correct type. event.emit(data) // This listener will only be called once. // You are *not* required to retain it. event.once { data: T in print(data) } // This listener won't stop listening; // unless you stop it manually, // or its Event<T> is deallocated. // You *are* required to retain it. var listener = event.on { data: T in print(data) } // Stop the listener manually. listener.isListening = false // Restart the listener (if it was stopped). listener.isListening = true
A target allows you to associate a specific AnyObject with an emit call. This is useful when emitting events associated with classes you can't add properties to (like UIView).
When calling emit with a target, you must also call on or once with the same target in order to receive the emitted event.
let myView = UIView() let didTouch = Event<UITouch>() didTouch.once(myView) { touch in print(touch) } didTouch.emit(myView, touch)
The Notifier class helps when you are forced to use NSNotificationCenter (for example, if you want to know when the keyboard has appeared).
// You are **not** required to retain this after creating your listener. var event = Notifier(UIKeyboardWillShowNotification) // Handle NSNotifications with style! listener = event.on { (userInfo: NSDictionary) in print(userInfo) }
// Any NSObject descendant will work. var view = UIView() // "Make KVO great again!" - Donald Trump listener = view.on("bounds") { (change: Change<CGRect>) in print(change) }
-
Swift 3.0 + Xcode 8.0 beta 6 support
-
The
Signalclass was removed. (useEvent<Void>instead) -
The
Emitterabstract class was removed. -
The
EmitterListenerclass was renamedEventListener<T>. -
The
Event<T>class no longer has a superclass. -
The
Notificationclass was renamedNotifier(to prevent collision withFoundation.Notification). -
The
onandoncemethods ofEvent<T>now return anEventListener<T>(instead of just aListener) -
The
onandoncemethods ofNotifiernow return anNotificationListener(instead of just aListener) -
The
onandoncemethods ofNSObjectnow return anChangeListener<T>(instead of just aListener) -
The
keyPath,options, andobjectproperties ofChangeListener<T>are now public. -
A
listenerCount: Intcomputed property was added to theEvent<T>class. -
An
event: Event<T>property was added to theEventListener<T>class.
The changelog for older versions can be found here.
- The
ChangeListenerclass may throw an exception (looking for help):
An -observeValueForKeyPath:ofObject:change:context: message was received but not handled.```