The Occupancy interface provides methods for tracking the number of users in a chat room. Access it via room.occupancy.
1
const occupancy = room.occupancy;Properties
The Occupancy interface has the following properties:
currentOccupancyData or Undefinedundefined if no occupancy events have been received yet since room attachment. Requires enableEvents to be true in the room's occupancy options.Get current occupancy
occupancy.get(): Promise<OccupancyData>Fetches the current occupancy of the chat room from the server. Retrieves the latest occupancy metrics, including the number of active connections and presence members.
This method uses the Ably Chat REST API and does not require the room to be attached.
1
2
3
const data = await room.occupancy.get();
console.log('Connections:', data.connections);
console.log('Presence members:', data.presenceMembers);Returns
Promise<OccupancyData>
Returns a promise. The promise is fulfilled with the current occupancy data, or rejected with an ErrorInfo object.
Subscribe to occupancy events
occupancy.subscribe(listener: OccupancyListener): SubscriptionSubscribes to occupancy updates for the chat room. Receives updates whenever the number of connections or present members in the room changes.
Requires enableEvents to be true in the room's occupancy options. The room should be attached to receive occupancy events.
1
2
3
4
5
6
7
const { unsubscribe } = room.occupancy.subscribe((event) => {
console.log('Connections:', event.occupancy.connections);
console.log('Presence members:', event.occupancy.presenceMembers);
});
// To stop receiving occupancy updates
unsubscribe();Parameters
The subscribe() method takes the following parameters:
listenerrequiredOccupancyEventReturns
Subscription
Returns an object with the following methods:
Unsubscribe from occupancy events
unsubscribe(): voidCall unsubscribe() to stop receiving occupancy events.
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
const room = await chatClient.rooms.get('my-room', {
occupancy: {
enableEvents: true // Required for subscribe() and current property
}
});
await room.attach();
// Subscribe to occupancy changes
const { unsubscribe } = room.occupancy.subscribe((event) => {
const { connections, presenceMembers } = event.occupancy;
console.log(`Room has ${connections} connections and ${presenceMembers} presence members`);
// Update UI with viewer count
document.getElementById('viewer-count').textContent = connections;
});
// Fetch occupancy on-demand (works even without enableEvents)
const occupancy = await room.occupancy.get();
console.log(`Initial occupancy: ${occupancy.connections} connections`);
// Access cached occupancy (requires enableEvents)
const cached = room.occupancy.current;
if (cached) {
console.log('Cached occupancy:', cached.connections);
}
// Clean up
unsubscribe();