In-memory event bus implementation.

Provides a simple, synchronous event bus with pub/sub capabilities. Each event type can have multiple subscribers.

const eventBus = new InMemoryEventBus();

// Subscribe to event
eventBus.subscribe(UserCreatedEvent, async (event) => {
await sendWelcomeEmail(event.userId);
});

eventBus.subscribe(UserCreatedEvent, async (event) => {
await logUserCreation(event.userId);
});

// Publish event
await eventBus.publish(new UserCreatedEvent('123', 'john@example.com'));

Implements

  • EventBus

Constructors

Methods

  • Subscribes to an event type.

    Multiple handlers can subscribe to the same event type.

    Type Parameters

    • TEvent extends Event

      The event type

    Parameters

    • eventType: new (...args: never[]) => TEvent

      The event class constructor

    • handler: EventHandler<TEvent> | (event: TEvent) => Promise<void>

      The handler function

    Returns void

    eventBus.subscribe(UserCreatedEvent, async (event) => {
    console.log('User created:', event.userId);
    });
  • Publishes an event to all subscribers.

    All handlers are invoked in parallel.

    Parameters

    • event: Event

      The event to publish

    Returns Promise<void>

    await eventBus.publish(new UserCreatedEvent('123', 'john@example.com'));
    
  • Publishes multiple events to their subscribers.

    Events are published in order, but handlers for each event run in parallel.

    Parameters

    • events: Event[]

      The events to publish

    Returns Promise<void>

    await eventBus.publishAll([
    new UserCreatedEvent('123', 'john@example.com'),
    new WelcomeEmailSentEvent('123')
    ]);
  • Unsubscribes a handler from an event type.

    Type Parameters

    • TEvent extends Event

      The event type

    Parameters

    • eventType: new (...args: never[]) => TEvent

      The event class constructor

    • handler: EventHandler<TEvent> | (event: TEvent) => Promise<void>

      The handler function to remove

    Returns void

    const handler = async (event) => console.log(event);
    eventBus.subscribe(UserCreatedEvent, handler);
    eventBus.unsubscribe(UserCreatedEvent, handler);
  • Gets the number of subscribers for an event type.

    Parameters

    • eventType: new (...args: never[]) => Event

      The event class constructor

    Returns number

    The number of subscribers

  • Clears all subscribers for a specific event type.

    Parameters

    • eventType: new (...args: never[]) => Event

      The event class constructor

    Returns void