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

Events are used for actors to publish updates to clients. Clients call actions to communicate with the actor.

Publishing from actors

Actors can publish events to clients using c.broadcast and conn.send.

Broadcasting events

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

import { actor } from "actor-core";

const chatRoom = actor({
  state: {},
  actions: {
    sendMessage: (c, message) => {
      c.broadcast('newMessage', { message });
    }
  }
});

Sending events to specific connections

Actors can send messages to specific client connections. All connections are available through the context object. For example:

import { actor } from "actor-core";

const chatRoom = actor({
  state: {},
  actions: {
    sendPrivateMessage: (c, connId, message) => {
      const conn = c.conns.find(conn => conn.id === connId);
      if (conn) {
        conn.send('newMessage', { message });
      }
    }
  }
});

Subscribing from clients

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

on(eventName, callback)

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

import { createClient } from "actor-core/client";
import type { App } from "./src/index";

const client = createClient<App>("http://localhost:6420");
const chatRoom = await client.chatRoom.get();

chatRoom.on('newMessage', ({ message }) => {
  console.log('Message', message);
});

once(eventName, callback)

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

import { createClient } from "actor-core/client";
import type { App } from "./src/index";

const client = createClient<App>("http://localhost:6420");
const chatRoom = await client.chatRoom.get();

chatRoom.once('joinRequestApproved', () => {
  // This will only be called once
  console.log('Join request accepted');
});

await chatRoom.requestJoin();

Connections

Connections are used to communicate with clients from the actor.

Read more about connections here.