Using Subscription Token

Every subscribing statement returns a unique Subscription Token in result.

var subscriptionToken = aggregator.get('some event').add(listener);

Subscription Token is used by event to identify subscription. Multiple subscribing statements for the same listener will return different tokens in result:

var token1 = aggregator.get('some event').add(listener);
var token2 = aggregator.get('some event').add(listener);

console.log(token1 === token2); // false.

Subscription Token also provides ability to unsubscribe listener. If you want to stop a listener from listening to an event, you can destroy the issued token by calling .destroy() on it:

// unsubscribes by destroying the issued token
token.destroy();

Event subscriptions will remain in memory until you either unset your Event Aggregator or unsubscribe all listeners or stop the application. The rule of thumb is that all no-longer-used listeners must be unsubscribed to release strong references between the listeners and Event Aggregator, thus avoids potential memory leak issues.

One-time Token

One-time Token allows you to declare some particular listeners which listen to event just only once and will be automatically unsubscribed after handling event. To make a token one-time, let event handling function destroy the token. Below is an example:

var token = aggregator.get('some event').add(payload => {
    token.destroy();
    console.log('Catch: ' + payload);
});

aggregator.get('some event').dispatch('first');
aggregator.get('some event').dispatch('second'); // will not be handled.

Console output:

Catch: first

Composite Token

This is a specialized subscription token and can contain other tokens. Upon destroying a Composite Token, all child tokens inside it will also be destroyed.

To create a Composite Token:

const { CompositeToken } = require('robo-toolkit').event;
var compositeToken = new CompositeToken();

You can add any token to this Composite Token at anytime:

compositeToken.add(token);

Or

compositeToken.add(aggregator.get('some event').add(listener));

Or by using .combineWith() with builder:

aggregator.get('some event').combineWith(compositeToken).add(listener);

Destroying a Composite Token will also destroy tokens inside it:

compositeToken.destroy(); // no needs to call token.destroy() anymore.

Composite Token is useful in case of you want to group some subscriptions together and then release them all at once.

Last updated