Occupancy
Occupancy enables you to view the number of users currently online in a room. This feature can be used to display user counts to highlight popular, or trending chat rooms.
Subscribe to room occupancy
Subscribe to a room's occupancy by registering a listener. Occupancy events are emitted whenever the number of online users within a room changes. Use the occupancy.subscribe() method in a room to receive updates:
1
2
3
const {unsubscribe} = room.occupancy.subscribe((event) => {
console.log(event);
});Occupancy event structure
The following is the structure of an occupancy event:
1
2
3
4
5
6
7
{
"type": "occupancy.updated",
"occupancy": {
"connections": 103,
"presenceMembers": 95
}
}The following are the properties of an occupancy event:
| Property | Description | Type |
|---|---|---|
| type | The type of the occupancy event. | String |
| occupancy | The occupancy data for the room. | OccupancyData |
connections: The number of connections in the room. | Number | |
presenceMembers: The number of users entered into the presence set of the room. | Number |
Unsubscribe from room occupancy
Use the unsubscribe() function returned in the subscribe() response to remove a room occupancy listener:
1
2
3
4
5
6
7
// Initial subscription
const { unsubscribe } = room.occupancy.subscribe((event) => {
console.log(event);
});
// To remove the listener
unsubscribe();Current room occupancy
The latest occupancy received in realtime (the same mechanism that powers occupancy subscriptions) can be retrieved in a one-off call.
Use the occupancy.current property to retrieve the most recently received room occupancy:
1
const occupancy = room.occupancy.current;The following is the structure of the occupancy data:
1
2
3
4
{
"connections": 103,
"presenceMembers": 95,
}The following are the properties of the occupancy data:
| Property | Description | Type |
|---|---|---|
| connections | The number of connections in the room. | Number |
| presenceMembers | The number of users entered into the presence set of the room. | Number |
Retrieve room occupancy
The occupancy of a room can be retrieved in one-off calls instead of subscribing to updates.
Use the occupancy.get() method to retrieve the occupancy of a room:
1
const occupancy = await room.occupancy.get();The following is the structure the occupancy data:
1
2
3
4
{
"connections": 103,
"presenceMembers": 95,
}The following are the properties of an occupancy data:
| Property | Description | Type |
|---|---|---|
| connections | The number of connections in the room. | Number |
| presenceMembers | The number of users entered into the presence set of the room. | Number |