A tiny typed messaging system inspired by js-signals that uses ES2015 sets
Path to Version 2
Version 2 of micro-signals will introduce some breaking interface changes. Most notably will be a shift from using bindings to a remove method on the signal itself. While bindings were a very nice interface, these changes will allow us to achieve late listener support (memorized signals) in a synchronous signal with a reduced chance for user error.
Previously, adding late listener support had been put off due to the inability to access the return value of a listener during the initial cached dispatch of the signal (which would need to happen while adding the signal). In addition, attempting to use the binding could throw an error during the initial call if the user did not check for the availability of a binding. We considered several ways around these issues:
Make micro-signals asynchronous
If a dispatch always calls the listener asynchronously then the binding is always available during the initial call of the listener function, whether a cached value or not. However, some projects may require the use of micro-signals in an environment where asynchronous behavior is not desirable or easy to implement. A synchronous signal still supports asynchronous dispatching (an asynchronous action can be triggered from the listener), but an asynchronous signal does not allow for synchronous action dispatching.
Pass a binding to the listener
This would ensure that the listener always had a valid reference to the binding. However, the user still needs a way to detach a listener that has not been called yet which, if we continued to use the binding interface, would mean there is still a binding returned from the add function. This could be an easy spot for user error, as forgetting to use the binding passed into a listener would cause the same errors mentioned above.
Do not use bindings
If we use add and remove methods on signals, we can be sure we are always able to remove during a listener add operation.
Several variations of the above were considered, but at the end of it all, option 3 seemed to be the cleanest way to provide a synchronous signal with late listener support that avoided the most opportunities for user error.
In order to add some of the convenience of bindings back to the API, there are plans to add the ability to tag a listener and then remove listeners based on either listener or tags.
The library has no relation to mini-signals and the name micro-signals is not meant to imply that this library is smaller than mini-signals in any way. The package was named and published before it was noticed that there already was a mini-signals library. Also, it may not seem very "micro" at this point. The original implementation was much smaller and at the time the name made more sense. However, the hope is that this library can provide a very useful signal interface and remain as "micro" as possible.
npm install micro-signals.
Basic Usage of a Signal
Listeners can also be added and removed with tags. Tags can be provided with the listener to the add function. If remove is then called with the listener or tag, the listener will be correctly removed. An example might be tagging a listener with an instance of the class from within a class, we can then remove the listener with only the reference to this. This functionality is provided to partially mitigate the loss of bindings and the difficulty that keeping track of listeners can pose in some cases. However, this interface does not provide the full convenience of bindings. If there are any ideas on improvements in this area, suggestions are welcome.
Using the Extended Signal Interface
;;;;signal.filterpayload === 'world'.map`hello !`.addreceived.pushpayload;signal.filterpayload === 'moon'.map`goodnight !`.addreceived.pushpayload;signal.dispatch'world';signal.dispatch'sun';signal.dispatch'moon';assert.deepEqualreceived, ;
Signal.merge takes an arbitrary number of signals as constructor arguments and forward payloads from all of the provided signals to the returned signal. This allow multiplexing of Signals. This matches the behavior of the Signal.merge instance method.
Turn signals into promises. The first argument is a resolution signal. When the resolution signal is dispatched the promise will be resolved with the dispatched value. The second argument is an optional rejection signal. When the rejection signal is dispatched the promise will be rejected with the dispatched value. This matches the behavior of the Signal.promisify instance method.
Signal.cache is used to provide late listener support to signals. It takes a cache instance that is responsible for determining what values are dispatched to late listeners, and returns a signal that will provide all cached values to new listeners.
These caches implement a simple interface consisting of an add function to process values that have been dispatched by the base signal and a forEach function to iterate over values that should be provided to late listeners.
Two basic cache types are provided to cover the most common use cases for cached signals. ValueCache replays the most recent value (similar to memorize in js-signals) and CollectionCache replays all dispatched values.
;;;;;;;.forEachsignal.dispatchpayload;valueCached.addvalueCachedReceived.pushpayload;collectionCached.addcollectionCachedReceived.pushpayload;.forEachsignal.dispatchpayload;assert.deepEqualvalueCachedReceived, ;assert.deepEqualcollectionCachedReceived, ;
Please note, there is currently not a way to unbind the cached signal from its base signal. This has the potential to leak attached listeners. In practice this may not be an issue for most use cases. Many use cases may have the base signal and the cached signal on the same object. For example:
;;;toggleState.setStatetrue;;toggleState.stateChanged.addstate = toggleState;assert.strictEqualstate, true;
In this case both signals will become unreachable at the same time, and therefore the base signal will never prevent any cleanup of the cached signal and its context. In many other cases this leaking may be negligible as well. However, if this functionality is desired, please file an issue or pull request against the repository.
readOnly provides a wrapper around a signal with no dispatch method. This is primarily used to publicly expose a signal while indicating that consumers of the signal should not dispatch the signal.
;;;;;readOnlySignal.add;assert.equalreadOnlySignal as any.dispatch, undefined;signal.dispatch'a';assert.deepEqualreceived, ;
Signal.filter also returns a signal of the correct type when filtering using a type predicate.
Signal.merge takes an arbitrary number of signals as constructor arguments and forward payloads from all of the provided signals and the base signal. This allow multiplexing of Signals. Effectively it merges the provided signals with the base signal.
Turn signals into promises. The base signal is a resolution signal. When the resolution signal is dispatched the promise will be resolved with the dispatched value. The second argument is an optional rejection signal. When the rejection signal is dispatched the promise will be rejected with the dispatched value.
An ExtendedSignal class is provided for the creation of a custom signal or wrapping a basic signal (containing only an add method) with the remainder of the methods found on a micro-signals Signal (such as map, filter, and so on). In many cases this gives us an easy way to ensure an intermediate Signal does not block garbage collection, and in some cases may present a simpler way to obtain a desired interface. For example, this makes it possible to extend the ExtendedSignal class to get the Signal interface without having to expose the add method anywhere.
Compare the following code examples:
;;;;;;signal.mapx + 1.addreceived.pushpayload;emitter.emit'event', 1;emitter.emit'event', 2;assert.deepEqualreceived, ;
;;;;;emitter.on'event', signal.dispatchpayload;;signal.mapx + 1.addreceived.pushpayload;emitter.emit'event', 1;emitter.emit'event', 2;assert.deepEqualreceived, ;
Though the second is more terse, there is always a listener connected to the underlying emitter object. In some cases this may prevent proper garbage collection. In the top example, the Signal only acts as a transformation layer, transforming listeners to provide the interface of a Signal without storing any state itself. This is how the internal signal transformations work in order to remove unnecessary intermediate signals. Feel free to use or ignore the ExtendedSignal at your discretion.
Default listeners allow the signal owner to define some default action that should be taken when a signal is dispatched but no listeners have been added. Typically this would be used to throw or log an error if no listeners are present for an important signal.
Default listeners can be set with either the static setDetaultListener method or the instance setDefaultListener method.
The static default listener will be called on any signal that has no listeners present (even if no instance default listener is set).
The instance default listener will only be called when the specific signal instance is dispatched with no listeners present.
;;// static default listener;;Signal.setDefaultListenerstaticPayloads.pushpayload;signal.dispatch'hello static listener';assert.equalstaticPayloads.length, 1;assert.equalstaticPayloads, 'hello static listener';// instance default listener;signal.setDefaultListenerinstancePayloads.pushpayload;signal.dispatch'hello instance listener';// static default listener is not used once instance default listener has been set.assert.equalstaticPayloads.length, 1;assert.equalinstancePayloads.length, 1;assert.equalinstancePayloads, 'hello instance listener';
Several interfaces are exported as well for convenience:
- Listener is an interface that defines a function that can be passed to Signal methods taking a listener (such as add or addOnce).
- ReadableSignal is an interface for a Signal without dispatch.
- WritableSignal only defines the dispatch method.
;;;// A ReadableSignal cannot be dispatched;readable.addlistener;// A WritableSignal can be dispatched;writable.dispatch'hello!';