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
- Add
onSubscribeto the viewers stream - incrementviewerCountand publish it - Add
onUnsubscribe- decrementviewerCountand publish it
Open both previews to see the viewer count update as users connect.
WebSocket
0
No messages yet