0/24
15. Lifecycle Hooks

Lesson 15: Lifecycle Hooks

Streams can react to clients connecting and disconnecting with lifecycle hooks:

live.stream('topic', () => value, {
  merge: 'set',
  onSubscribe: (ctx, topic) => {
    // a client just subscribed
  },
  onUnsubscribe: (ctx, topic) => {
    // a client just disconnected
  }
});

These are useful for tracking active viewers, cleaning up resources, or sending "user left" notifications.

Try it

  1. Add onSubscribe to the viewers stream - increment viewerCount and publish it
  2. Add onUnsubscribe - decrement viewerCount and publish it

Open both previews to see the viewer count update as users connect.

WebSocket
0
No messages yet
User A
User B