Presence

Presence Properties

The Presence object exposes the following public properties:

syncComplete

A boolean field indicating whether the presence member set is synchronized with server after a channel attach.

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

Methods

enter

In order to enter and be present on a channel, the client must be identified by having a client ID, have permission to be present, and be attached to the channel. For simplicity, the library will implicitly attach to a channel when entering. Entering when already entered is treated as an update.

enter(Object data?): Promise<void>

Enter a presence channel with optional data that is associated with the current present member. If the channel is initialized (i.e. no attempt to attach has yet been made for this channel), then calling enter will implicitly attach the channel.

Parameters

ParameterDescriptionType
datadata payload for the current present member. The supported payload types are Strings, JSON objects and arrays, buffers containing arbitrary binary data, and null.Object

Returns

Returns a promise. On success, the promise resolves. On failure, the promise is rejected with an ErrorInfo object that details the reason why it was rejected.

leave

In order to leave the presence set of a channel, the client must have already entered and been present.

leave(Object data?): Promise<void>

Leave a presence channel and emit an optional data that is associated with the current leaving member.

Parameters

ParameterDescriptionType
datadata payload for the current present member. The supported payload types are Strings, JSON objects and arrays, buffers containing arbitrary binary data, and null.Object

Returns

Returns a promise. On success, the promise resolves. On failure, the promise is rejected with an ErrorInfo object that details the reason why it was rejected.

update

Clients can update their member data on the channel which will trigger a broadcast of this update 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.

update(Object data?): Promise<void>

Update the current member's data and broadcast an update event to all subscribers. data may be null. If the channel is initialized (i.e. no attempt to attach has yet been made for this channel), then calling update will implicitly attach the channel.

Parameters

ParameterDescriptionType
datadata payload for the current present member. The supported payload types are Strings, JSON objects and arrays, buffers containing arbitrary binary data, and null.Object

Returns

Returns a promise. On success, the promise resolves. On failure, the promise is rejected with an ErrorInfo object that details the reason why it was rejected.

get

Get the current presence member set for this channel. Typically, this method returns the member set immediately as the member set is retained in memory by the client. However, by default this method will wait until the presence member set is synchronized, so if the synchronization is not yet complete following a channel being attached, this method will wait until the presence member set is synchronized.

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

When a channel is initialized (i.e. no attempt to attach has yet been made for this channel), then calling get will implicitly attach the channel.

get(Object params?): Promise<PresenceMessage[]>

Gets an array of members present on the channel as PresenceMessage objects.

Parameters

ParameterDescriptionType
paramsan optional object containing query parameters as specified below.

params parameters

PropertyDescriptionType
clientIdwhen provided, will filter array of members returned that match the provided clientId stringString
connectionIdwhen provided, will filter array of members returned that match the provided connectionId stringString
waitForSyncA boolean value that by default waits for the initial presence synchronization following channel attachment to complete before returning the members present. When false, the current list of members is returned without waiting for a complete synchronization.
Default: true
Boolean

Returns

Returns a promise. On success, the promise is fulfilled with an array of PresenceMessage objects corresponding to the current set of present members on the channel. On failure, the promise is rejected with an ErrorInfo object that details the reason why it was rejected.

history

history(Object params?): Promise<PaginatedResult<PresenceMessage>>

Gets a paginated set of historical presence message events for this channel. If the channel is configured to persist messages to disk then the presence message event 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.

Parameters

ParameterDescriptionType
paramsan optional object containing query parameters, as specified in the presence history API documentation

Further details of the supported options params, see presence history API documentation

Returns

Returns a promise. On success, the promise is fulfilled with a PaginatedResult object containing an array of PresenceMessage objects corresponding to the current page of results. On failure, the promise is rejected with an ErrorInfo object that details the reason why it was rejected.

subscribe

There are overloaded versions of this method:

subscribe(listener(PresenceMessage)): Promise<void>

Subscribe to presence message events on this channel. The caller supplies a listener function, which is called each time one or more presence events occurs such as a member entering or leaving a channel.

subscribe(String action, listener(PresenceMessage)): Promise<void>

Subscribe to presence message events with a given action on this channel. The caller supplies a listener function, which is called each time one or more presence events occurs such as a member entering or leaving a channel.

subscribe(String[] actions, listener(PresenceMessage))

Subscribe a single listener to messages on this channel for multiple action values.

Parameters

ParameterDescriptionType
actionThe presence action event to subscribe toString
actionsAn array of action events to subscribe toString[]
listeneris a function of the form function(presenceMessage) to be called for each matching presence message event

Returns

Returns a promise. On successful channel attachment, the promise is resolved. On failure, the promise is rejected with an ErrorInfo object that details the reason why it was rejected.

Considerations

  • If the channel is initialized (i.e. no attempt to attach has yet been made for this channel), then calling subscribe will implicitly attach the channel. However, regardless of the implicit attach outcome, the listener will still be registered
  • If subscribe is called more than once with the same listener, then duplicates will be registered. For example, if you subscribe twice with the same listener and a presence message is later received, the same listener will be invoked twice
  • The registered listener remains active on the presence channel regardless of the underlying channel state. For example, if you call subscribe when the underlying channel is attached and it later becomes detached or even failed, when the channel is reattached and a presence message is received, the listeners originally registered will still be invoked. Listeners are only removed when calling unsubscribe or when the underlying channel is released using the Realtime.channels.release(name) method
  • If an exception is thrown in the subscribe listener and bubbles up to the event emitter, it will be caught and logged at error level, so as not to affect other listeners for the same event

unsubscribe

There are six overloaded versions of this method:

unsubscribe(String action, listener)

Unsubscribe the given listener from presence message events on this channel for the given action This removes an earlier event-specific subscription.

unsubscribe(listener)

Unsubscribe the given listener from presence message events on this channel. This removes an earlier subscription.

unsubscribe(String[] actions, listener)

Unsubscribe the given listener from all presence actions in the array.

unsubscribe(String action)

Unsubscribe all listeners for a given action

unsubscribe(String[] actions)

Unsubscribe all listeners for all presence actions in the array.

unsubscribe()

Unsubscribes all listeners to presence message events on this channel. This removes all earlier subscriptions.

Parameters

ParameterDescriptionType
actionThe presence action event to unsubscribe fromString
actionsAn array of actions to unsubscribe fromString[]
listeneris the callback listener function that was previously subscribed

enterClient

Enter this presence channel for the given clientId. This method is provided to support typically server instances that act on behalf of multiple client IDs. See Managing multiple client IDs for more info. In order to be able to publish presence changes for arbitrary client IDs, the client library must have been instantiated either with an API key or with a token bound to a wildcard client ID

enterClient(String clientId, Object data?): Promise<void>

Enter a presence channel on behalf of the provided clientId and provide an optional data that is associated with the current present member. If the channel is initialized (i.e. no attempt to attach has yet been made for this channel), then calling enter will implicitly attach the channel.

Parameters

ParameterDescriptionType
datadata payload for the member. The supported payload types are Strings, JSON objects and arrays, buffers containing arbitrary binary data, and null.Object

Returns

Returns a promise. On success, the promise resolves. On failure, the promise is rejected with an ErrorInfo object that details the reason why it was rejected.

leaveClient

Leave this presence channel for the given clientId. This method is provided to support typically server instances that act on behalf of multiple client IDs. See Managing multiple client IDs for more info. In order to leave the presence set of a channel, the client must have already entered and been present

leaveClient(String clientId, Object data?): Promise<void>

Leave a presence channel on behalf of the provided clientId and emit an optional data that is associated with the current leaving member.

Parameters

ParameterDescriptionType
datadata payload for the member. The supported payload types are Strings, JSON objects and arrays, buffers containing arbitrary binary data, and null.Object

Returns

Returns a promise. On success, the promise resolves. On failure, the promise is rejected with an ErrorInfo object that details the reason why it was rejected.

updateClient

Clients can update the member data on behalf of the given clientId which will trigger a broadcast of this update to all presence subscribers. This method is provided to support typically server instances that act on behalf of multiple client IDs. See Managing multiple client IDs for more info. If an attempt to update is made before the member has entered the channel, the update is treated as an enter.

A callback can optionally be passed in to be notified of success or failure to update the member data.

updateClient(String clientId, Object data?): Promise<void>

Update the member data on behalf of the provided clientId and broadcast an update event to all subscribers. data may be null. If the channel is initialized (i.e. no attempt to attach has yet been made for this channel), then calling enter will implicitly attach the channel.

Parameters

ParameterDescriptionType
datadata payload for the member. The supported payload types are Strings, JSON objects and arrays, buffers containing arbitrary binary data, and null.Object

Returns

Returns a promise. On success, the promise resolves. On failure, the promise is rejected with an ErrorInfo object that details the reason why it was rejected.

PresenceMessage

A PresenceMessage represents an individual presence update that is sent to or received from Ably.

Properties

PropertyDescriptionType
actionthe event signified by a PresenceMessage. See Presence actionint enum { ABSENT, PRESENT, ENTER, LEAVE, UPDATE }
dataThe presence update payload, if providedString, StringBuffer, JSON Object
extrasMetadata and/or ancillary payloads, if provided. The only currently valid payloads for extras are the push, ref and privileged objects.JSON Object
idUnique ID assigned by Ably to this presence updateString
clientIdThe client ID of the publisher of this presence updateString
connectionIdThe connection ID of the publisher of this presence updateString
timestampTimestamp when the presence update was received by Ably, as milliseconds since the epoch.Integer
encodingThis will typically be empty as all presence updates received from Ably are automatically decoded client-side using this value. However, if the message encoding cannot be processed, this attribute will contain the remaining transformations not applied to the data payloadString

PresenceMessage constructors

PresenceMessage.fromEncoded

PresenceMessage.fromEncoded(Object encodedPresMsg, ChannelOptions channelOptions?) -> PresenceMessage

A static factory method to create a PresenceMessage from a deserialized PresenceMessage-like object encoded using Ably's wire protocol.

Parameters

ParameterDescriptionType
encodedPresMsga PresenceMessage-like deserialized object.Object
channelOptionsan optional ChannelOptions. If you have an encrypted channel, use this to allow the library can decrypt the data.Object

Returns

A PresenceMessage object

PresenceMessage.fromEncodedArray

PresenceMessage.fromEncodedArray(Object[] encodedPresMsgs, ChannelOptions channelOptions?) -> PresenceMessage[]

A static factory method to create an array of PresenceMessages from an array of deserialized PresenceMessage-like object encoded using Ably's wire protocol.

Parameters

ParameterDescriptionType
encodedPresMsgsan array of PresenceMessage-like deserialized objects.Array
channelOptionsan optional ChannelOptions. If you have an encrypted channel, use this to allow the library can decrypt the data.Object

Returns

An Array of PresenceMessage objects

Presence action

Presence action is a String with a value matching any of the Realtime Presence states & events

JavaScript

1

2

3

4

5

6

7

var PresenceActions = [
  'absent', // (reserved for internal use)
  'present',
  'enter',
  'leave',
  'update'
]

PaginatedResult

A PaginatedResult is a type that represents a page of results for all message and presence history, stats and REST presence requests. The response from a Ably REST API paginated query is accompanied by metadata that indicates the relative queries available to the PaginatedResult object.

Properties

PropertyDescriptionType
itemscontains the current page of results (for example an Array of Message or PresenceMessage objects for a channel history request)Array <Message, Presence, Stats>

Methods

first

first(): Promise<PaginatedResult>

Returns a promise. On success, the promise is fulfilled with a new PaginatedResult for the first page of results. On failure, the promise is rejected with an ErrorInfo object that details the reason why it was rejected.

hasNext

Boolean hasNext()

Returns true if there are more pages available by calling next and returns false if this page is the last page available.

isLast

Boolean isLast()

Returns true if this page is the last page and returns false if there are more pages available by calling next available.

next

next(): Promise<PaginatedResult | null>

Returns a promise. On success, the promise is fulfilled with a new PaginatedResult loaded with the next page of results. If there are no further pages, then null is returned. On failure, the promise is rejected with an ErrorInfo object that details the reason why it was rejected.

current

current(): Promise<PaginatedResult>

Returns a promise. On success, the promise is fulfilled with a new PaginatedResult loaded with the current page of results. On failure, the promise is rejected with an ErrorInfo object that details the reason why it was rejected.

Example

JavaScript

1

2

3

4

5

const paginatedResult = await channel.history();
console.log('Page 0 item 0:' + paginatedResult.items[0].data);
const nextPage = await paginatedResult.next();
console.log('Page 1 item 1: ' + nextPage.items[1].data);
console.log('Last page?: ' + nextPage.isLast());
Select...