Events
Real-time communication between actors and clients
Events enable real-time communication from actors to clients. While clients use actions to send data to actors, events allow actors to push updates to connected clients instantly.
Info
Events work through persistent connections (WebSocket or SSE). Clients establish connections using .connect()
and then listen for events with .on()
.
Publishing Events from Actors
Broadcasting to All Clients
Use c.broadcast(eventName, data)
to send events to all connected clients:
Sending to Specific Connections
Send events to individual connections using conn.send(eventName, data)
:
Event Filtering by Connection State
Filter events based on connection properties:
Subscribing to Events from Clients
Clients must establish a connection to receive events from actors. Use .connect()
to create a persistent connection, then listen for events.
Basic Event Subscription
Use connection.on(eventName, callback)
to listen for events:
One-time Event Listeners
Use connection.once(eventName, callback)
for events that should only trigger once:
Removing Event Listeners
Use connection.off()
to remove event listeners:
React Integration
Rivet's React hooks provide a convenient way to handle events in React components:
Connection Lifecycle Events
Connections emit lifecycle events you can listen to:
Advanced Event Patterns
Event Buffering
Events are automatically buffered during disconnections and replayed on reconnection:
Connection Parameters
Pass parameters when connecting to provide context to the actor:
Conditional Event Handling
Handle events conditionally based on connection state:
Error Handling
Handle event-related errors gracefully:
Best Practices
- Always use connections for events: Events only work through
.connect()
, not direct action calls - Handle connection lifecycle: Listen for connection, disconnection, and error events
- Clean up listeners: Remove event listeners when components unmount
- Validate event data: Don't assume event payloads are always correctly formatted
- Use React hooks: For React apps, use
useActor
andactor.useEvent
for automatic cleanup - Buffer critical events: Design actors to resend important events on reconnection if needed