RealtimePresence
A RealtimePresence object enables a client to be present on a channel and to query and subscribe to the presence set; access it via the presence property of a RealtimeChannel instance.
1
const presence = channel.presence;Properties
The RealtimePresence interface has the following properties:
syncCompleteBooleanSubscribe to presence events
presence.subscribe(listener: presenceMessageCallback): Promise<void>Subscribe to presence events on the channel. The listener is invoked for every presence message received.
presence.subscribe(action: PresenceAction | PresenceAction[], listener?: presenceMessageCallback): Promise<void>Subscribe to presence events for a specific action (or array of actions). The listener is invoked only for matching events.
1
2
3
4
5
6
7
await channel.presence.subscribe((presenceMessage) => {
console.log(`${presenceMessage.action} from ${presenceMessage.clientId}`);
});
await channel.presence.subscribe('enter', (presenceMessage) => {
console.log(`${presenceMessage.clientId} entered`);
});Parameters
The subscribe() method takes the following parameters:
actionoptionalPresenceAction or PresenceAction[]listeneroptionalFunctionPresenceMessage for each matching event. Required when subscribing to all events; with an action argument it may be omitted to attach the channel without registering a listener.Returns
Promise<void>
Returns a promise. The promise is fulfilled when the channel has been attached and the subscription is active, or rejected with an ErrorInfo object.
Considerations
Note the following behaviours when subscribing to presence events:
- If the channel is
initialized(no attempt to attach has yet been made), callingsubscribe()implicitly attaches the channel. The listener is still registered regardless of the outcome of the implicit attach. - If
subscribe()is called more than once with the same listener, the listener is registered each time. For example, if you subscribe twice with the same listener and a presence message is later received, that listener is invoked twice. - The registered listener remains active regardless of the underlying channel state. For example, if the channel later becomes
detachedorfailedand is then reattached, listeners originally registered are still invoked when a presence message is received. Listeners are only removed by callingunsubscribe()or by releasing the underlying channel withrealtime.channels.release(name). - If an exception is thrown in a listener and bubbles up to the event emitter, it is caught and logged at
errorlevel so that it does not affect other listeners for the same event.
Enter the presence set
presence.enter(data?: any): Promise<void>Enter the presence set for the channel, optionally with data that is associated with the present member. In order to enter the presence set the client must be identified by having a client ID, have permission to be present, and be attached to the channel. The SDK will implicitly attach to the channel when entering. Entering when already entered is treated as an update().
1
await channel.presence.enter('status string');Parameters
The enter() method takes the following parameters:
dataoptionalAnynull.Returns
Promise<void>
Returns a promise. The promise is fulfilled when the client has entered the presence set, or rejected with an ErrorInfo object.
Update the present member
presence.update(data?: any): Promise<void>Update the current member's data on the channel. This broadcasts an update event to all presence subscribers. The pre-requisites for update() are the same as for enter(). If an attempt to update() is made before the client has entered the channel, the update is treated as an enter.
1
await channel.presence.update('new status');Parameters
The update() method takes the following parameters:
dataoptionalAnynull.Returns
Promise<void>
Returns a promise. The promise is fulfilled when the update has been delivered, or rejected with an ErrorInfo object.
Leave the presence set
presence.leave(data?: any): Promise<void>Leave the presence set for the channel. Optionally provide data to broadcast with the leave event. The client must already have entered the presence set.
1
await channel.presence.leave();Parameters
The leave() method takes the following parameters:
dataoptionalAnyReturns
Promise<void>
Returns a promise. The promise is fulfilled when the client has left the presence set, or rejected with an ErrorInfo object.
Get the presence set
presence.get(params?: RealtimePresenceParams): Promise<PresenceMessage[]>Retrieve the current members of the presence set for the channel. The returned array contains a PresenceMessage object for each member, with metadata such as the member's clientId, connectionId, action, and any associated data.
The member set is retained in memory by the client, so this method typically returns immediately. However, by default it waits until the presence member set is synchronized, so if synchronization is not yet complete after the channel attaches, it waits until synchronization is complete.
When a channel is attached, the Ably service synchronizes the presence member set with the client. This typically completes in milliseconds, however a very large member set may take longer.
When a channel is initialized (i.e. no attempt to attach has yet been made), calling get() will implicitly attach the channel.
1
2
const members = await channel.presence.get();
console.log(`${members.length} members present`);Parameters
The get() method takes the following parameters:
paramsoptionalRealtimePresenceParamsReturns
Promise<PresenceMessage[]>
Returns a promise. The promise is fulfilled with an array of PresenceMessage objects representing the current members of the presence set, or rejected with an ErrorInfo object.
Unsubscribe from presence events
presence.unsubscribe(action: PresenceAction | PresenceAction[], listener: presenceMessageCallback): voidRemove the listener for the specified PresenceAction.
presence.unsubscribe(action: PresenceAction | PresenceAction[]): voidRemove all listeners registered against the specified action(s).
presence.unsubscribe(listener: presenceMessageCallback): voidRemove the specified listener from all presence actions.
presence.unsubscribe(): voidRemove all listeners.
1
channel.presence.unsubscribe();Parameters
The unsubscribe() method takes the following parameters:
actionoptionalPresenceAction or PresenceAction[]listeneroptionalFunctionGet presence history
presence.history(params?: RealtimeHistoryParams): Promise<PaginatedResult<PresenceMessage>>Get a paginated set of historical presence message events for the channel. If the channel is configured to persist messages, the presence message history will typically be available for 24 - 72 hours. If not, presence message events are only retained in memory by the Ably service for two minutes.
1
2
3
4
const history = await channel.presence.history({ limit: 50 });
history.items.forEach((member) => {
console.log(member.action, member.clientId);
});Parameters
The history() method takes the following parameters:
paramsoptionalRealtimeHistoryParamsReturns
Promise<PaginatedResult<PresenceMessage>>
Returns a promise. The promise is fulfilled with a PaginatedResult containing an array of PresenceMessage objects, or rejected with an ErrorInfo object.
Enter the presence set on behalf of a client
presence.enterClient(clientId: string, data?: any): Promise<void>Enter the presence set on behalf of the given client ID. This is useful when a single client is acting on behalf of multiple clients, for example a server-side process managing presence for multiple client IDs. Requires the client to be authenticated with a clientId matching the supplied value, or with a wildcard clientId. The wildcard requirement can be satisfied with an API key, or a token bound to a wildcard client ID.
1
await channel.presence.enterClient('user-123', 'status');Parameters
The enterClient() method takes the following parameters:
clientIdrequiredStringdataoptionalAnyReturns
Promise<void>
Returns a promise. The promise is fulfilled when the client has been entered into the presence set, or rejected with an ErrorInfo object.
Update a client's presence data
presence.updateClient(clientId: string, data?: any): Promise<void>Update the data for an existing present member on behalf of the given client ID. If the client is not already in the presence set, this is treated as an enterClient().
1
await channel.presence.updateClient('user-123', 'new status');Parameters
The updateClient() method takes the following parameters:
clientIdrequiredStringdataoptionalAnyReturns
Promise<void>
Returns a promise. The promise is fulfilled when the update has been delivered, or rejected with an ErrorInfo object.
Leave the presence set on behalf of a client
presence.leaveClient(clientId: string, data?: any): Promise<void>Leave the presence set on behalf of the given client ID. Requires the same authentication conditions as enterClient().
1
await channel.presence.leaveClient('user-123');Parameters
The leaveClient() method takes the following parameters:
clientIdrequiredStringdataoptionalAnyReturns
Promise<void>
Returns a promise. The promise is fulfilled when the client has left the presence set, or rejected with an ErrorInfo object.