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.

JavaScript

1

const presence = channel.presence;

Properties

The RealtimePresence interface has the following properties:

syncCompleteBoolean
Indicates whether the presence member set is synchronized with the server after a channel attach. When a channel is attached, the Ably service immediately synchronizes the presence member set with the client. Typically this completes in milliseconds, however when the presence member set is very large, bandwidth constraints may slow this synchronization down.

Subscribe 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.

JavaScript

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[]
The presence action(s) to subscribe to. If omitted, the listener fires for every presence event.
listeneroptionalFunction
A function invoked with a PresenceMessage 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), calling subscribe() 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 detached or failed and is then reattached, listeners originally registered are still invoked when a presence message is received. Listeners are only removed by calling unsubscribe() or by releasing the underlying channel with realtime.channels.release(name).
  • If an exception is thrown in a listener and bubbles up to the event emitter, it is caught and logged at error level 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().

JavaScript

1

await channel.presence.enter('status string');

Parameters

The enter() method takes the following parameters:

dataoptionalAny
The data payload for the present member. Supported payload types are strings, JSON objects and arrays, buffers containing arbitrary binary data, and null.

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.

JavaScript

1

await channel.presence.update('new status');

Parameters

The update() method takes the following parameters:

dataoptionalAny
The new data payload for the present member. May be null.

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.

JavaScript

1

await channel.presence.leave();

Parameters

The leave() method takes the following parameters:

dataoptionalAny
The data payload to broadcast with the leave event.

Returns

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.

JavaScript

1

2

const members = await channel.presence.get();
console.log(`${members.length} members present`);

Parameters

The get() method takes the following parameters:

paramsoptionalRealtimePresenceParams
Filter and synchronization options for the query.

Returns

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): void

Remove the listener for the specified PresenceAction.

presence.unsubscribe(action: PresenceAction | PresenceAction[]): void

Remove all listeners registered against the specified action(s).

presence.unsubscribe(listener: presenceMessageCallback): void

Remove the specified listener from all presence actions.

presence.unsubscribe(): void

Remove all listeners.

JavaScript

1

channel.presence.unsubscribe();

Parameters

The unsubscribe() method takes the following parameters:

actionoptionalPresenceAction or PresenceAction[]
The action(s) to unsubscribe from.
listeneroptionalFunction
The specific listener to remove. If omitted, all matching listeners are removed.

Get 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.

JavaScript

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:

paramsoptionalRealtimeHistoryParams
Query parameters as specified in the presence history API documentation.

Returns

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.

JavaScript

1

await channel.presence.enterClient('user-123', 'status');

Parameters

The enterClient() method takes the following parameters:

clientIdrequiredString
The client ID to enter the presence set on behalf of.
dataoptionalAny
The data payload for the present member.

Returns

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().

JavaScript

1

await channel.presence.updateClient('user-123', 'new status');

Parameters

The updateClient() method takes the following parameters:

clientIdrequiredString
The client ID whose data is to be updated.
dataoptionalAny
The new data payload.

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 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().

JavaScript

1

await channel.presence.leaveClient('user-123');

Parameters

The leaveClient() method takes the following parameters:

clientIdrequiredString
The client ID to remove from the presence set.
dataoptionalAny
The data payload to broadcast with the leave event.

Returns

Promise<void>

Returns a promise. The promise is fulfilled when the client has left the presence set, or rejected with an ErrorInfo object.