DocsGuidesPub/Sub

Pub/Sub (Topics)

TopGun provides a distributed Publish/Subscribe mechanism via Topics. Unlike Maps, messages sent over topics are ephemeral—they are not stored in the database and are delivered only to currently connected subscribers.

Real-time Notifications

"User X is typing...", "New alert!", presence updates, and more.

Signaling

Perfect for WebRTC offer/answer exchange and coordination.

Live Events

Stock tickers, mouse movements, game state updates.

Subscribing

Use client.topic(name) to get a topic handle, then call .subscribe(). The callback receives the data and context (timestamp, publisher).

src/pubsub/chat.ts
const chatTopic = client.topic('chat-room:general');

const unsubscribe = chatTopic.subscribe((data, context) => {
  console.log('Received:', data);
  // context.publisherId is optional (undefined if sent from server/system)
  console.log('From:', context.publisherId);
  console.log('At:', new Date(context.timestamp));
});

// Later, to stop listening:
// unsubscribe();

Publishing

Publishing is “fire-and-forget”. The message goes to the server and is relayed to all other nodes subscribed to that topic.

src/pubsub/publish.ts
// Send a simple string
chatTopic.publish('Hello World');

// Or an object
chatTopic.publish({
  type: 'typing',
  user: 'Alice'
});

Key Behaviors

  • No Persistence: If a user is offline when a message is sent, they will not receive it upon reconnecting. Use getMap() or getORMap() if you need history.
  • Re-subscription: The client automatically re-subscribes to topics upon reconnection to the server.
  • Delivery Guarantee: Best-effort. Messages are not ACKed for persistence.