Skip to main content

Event Bus

The event bus is an object that can be obtained through the events property of the sdk. It is used to subscribe to events issued by Alfa clients and services.

const eventBus = sdk.events;

Subscribe to an event

The event bus has a registerHandler method that allows you to subscribe to an event. This method receives as a parameter the name of the event to which it is desired to subscribe and an asynchronous function that will be executed each time the event is emitted.

eventBus.registerHandler<MintAssetEvent>(MintAssetEvent.eventName, async (event) => {
console.log(`New asset minted: ${event.payload.asset.assetId}`);
});
Event typing

The registerHandler function is generic and takes as a parameter the type of event to which you want to subscribe. This allows the function that is executed when the event is emitted to have access to the payload of the event with the correct type.

caution

The registration function must be asynchronous for sdk design considerations.

Event names

Event names can be obtained via the eventName property of each event. See the section List of available events to see the list of available events.

Unsubscribe from an event

The registerHandler function returns an EventSubscription type object that allows you to unsubscribe from the event you subscribed to. To unsubscribe, you must call the unsubscribe method of the EventSubscription object.

const subscription = eventBus.registerHandler<MintAssetEvent>(MintAssetEvent.eventName, async(event) => {
console.log(`New asset minted: ${event.payload.asset.assetId}`);
});

subscription.unsubscribe(); // Stop listening for the event

Support for rxjs

The EventSubscription object is compatible with the rxjs Subscription interface, so you can use the rxjs unsubscribe method to unsubscribe from an event.

const subs$ = new Subscription(); // This is from rxjs

subs$.add(eventBus.registerHandler<MintAssetEvent>(MintAssetEvent.eventName, async(event) => {
console.log(`New asset minted: ${event.payload.asset.assetId}`);
}));

subs$.unsubscribe(); // Stop listening for the event