Subscribing to Events

Events provide a mechanism to transfer data to connections that subscribe to them. They form the backbone of Relaybox services as an event-driven system.

Subscribing to All Events

When a connection joins a room, it can either process all data sent to the room or subscribe to specific events of interest. To subscribe to all events sent to a specific room, simply pass your event handler as the first argument when creating the subscription.

const myRoom = await relayBox.join('myRoom');

await myRoom.subscribe((data) => {
  // All data sent to "myRoom" will be handled here
  console.log(data)
});

This approach is useful if you are interested in receiving all events for a room. However, if you would prefer to receive only certain named events, the syntax is slightly different.

Subscribing to Named Events

When joining a room, it is common to subscribe to named events depending on the data you wish to receive.

const myRoom = await relayBox.join('myRoom');

await myRoom.subscribe('eventOne', (data) => {
  // Only "eventOne" events will be received
  console.log(data)
});

This method can reduce traffic and cost as it allows you to filter a subset of events. Unlike other systems, you will only be sent the events you are subscribed to, rather than subscriptions just acting as a filter at the room level.

    On this page