Build with Rivet

Events

Events are used for clients to receive realtime data from actors.


Publishing from actors

Actors can publish events to clients using this.broadcast and connection.send.

Broadcasting events

Actors can publish events to all connected clients with this.broadcast(name, data). For example:

class ChatRoom extends Actor {
  sendMessage(rpc: Rpc<this>, message: string) {
    this.broadcast('newMessage', { message });
  }
}

Sending events to specific connections

Actors can send messages to specific client connections. All connections are available on the this.connections array. For example:

class ChatRoom extends Actor {
  sendPrivateMessage(rpc: Rpc<this>, connectionId: number, message: string) {
    const conn = this.connections.find(c => c.id == connectionId);
    conn.send('newMessage', { message });
  }
}

Subscribing from clients

Clients can subscribe to events from actors using on and once.

on

Clients can subscribe to events that will happen repeatedly using actor.on(name, callback).

For example:

const actor = client.get<ChatRoom>({ name: 'chat_room' });
actor.on('newMessage', ({ message }) => {
  console.log('Message', message);
});

once

Clients can listen for an event only one time with actor.once(name, callback).

For example:

const actor = client.get<ChatRoom>({ name: 'chat_room' });
actor.once('joinRequestApproved', () => {
  // This will only be called once
  console.log('Join request accepted');
});
await actor.requestJoin();

Connections

Connections are used to communicate with clients from the actor.

Read more about connections here.