Channels
Channels
The Channels
object, accessed from the realtime library client constructor, is used to create and destroy Channel
objects. It exposes the following public methods:
Channels Methods
get
Channel get(String name, ChannelOptions channelOptions?)
Creates a new Channel object if none for the channel exists, or returns the existing channel object.
getDerived
Channel get(String name, DeriveOptions deriveOptions, ChannelOptions channelOptions?)
Creates a new Channel object if none for the channel exists, or returns the existing channel object. The Channel object is created or returned with the specified DeriveOptions
and optional ChannelOptions
.
Derived channels enables you to subscribe to a filtered subset of messages on a channel. See subscription filters for more information.
release
release(String channelName)
Releases a Channel object, deleting it and enabling it to be garbage collected. It also removes any listeners associated with the channel.
Note: To release a channel, the channel state must be initialized
, detached
or failed
.
Channel
The Channel object, created via the Channels object, is used to interact with a specific channel.
Channel Properties
The Channel
object exposes the following public properties:
state
The current ChannelState
of this Channel
. See the supported channel states for more information.
errorReason
When a channel failure occurs this property is populated.
The type is ErrorInfo
.
name
The name String
unique to this channel.
presence
Provides access to the Presence object for this channel which can be used to access members present on the channel, or participate in presence.
push
Provides access to the PushChannel object for this channel which can be used to access members present on the channel, or participate in presence.
objects
Provides access to the Objects object for this channel which can be used to read, modify and subscribe to LiveObjects on a channel.
params
The current channel parameters configured for this channel.
modes
The current channel modes configured for this channel.
Methods
publish
There are three overloaded versions of this method:
publish(String name, Object data): Promise<void>
Publish a single message on this channel based on a given event name and payload. When publish is called with this client library, it won’t attempt to implicitly attach to the channel, so long as transient publishing is available in the library. Otherwise, the client will implicitly attach.
publish(Object message): Promise<void>
Publish a single message on this channel. When publish is called with this client library, it won’t attempt to implicitly attach to the channel, so long as transient publishing is available in the library. Otherwise, the client will implicitly attach.
publish(Object[] messages): Promise<void>
Publish several messages on this channel. When publish is called with this client library, it won’t attempt to implicitly attach to the channel. If the channel is initialized
(i.e. no attempt to attach has yet been made for this channel), then calling publish
will implicitly attach the channel.
The entire messages
array is published atomically. This means that:
- Either they will all be successfully published or none of them will
- The max message size limit applies to the total size of all messages in the array
- The publish will only count as a single message for the purpose of per-channel rate limit
- If you are using client-specified message IDs, they must conform to certain restrictions
Parameters
- data
- data payload for the message. The supported payload types are Strings, objects or arrays capable of JSON representation, buffers containing arbitrary binary data, and null. (Note that if sending a binary, that binary should be the entire payload; an object with a binary field within it may not be correctly encoded)Type:
Object
- message
- A message object to publishType:
Message
- messages
- An array of message objects to publishType:
Message []
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.
subscribe
There are overloaded versions of this method:
subscribe(listener): Promise<null | ChannelStateChange>
Subscribe to messages on this channel. The caller supplies a listener function, which is called each time one or more messages arrives on the channel.
subscribe(String event, listener?): Promise<null | ChannelStateChange>
Subscribe to messages with a given event name on this channel. The caller supplies a listener function, which is called each time one or more matching messages arrives on the channel.
subscribe(String[] events, listener?): Promise<null | ChannelStateChange>
Subscribe a single listener to messages on this channel for multiple event name
values.
subscribe(filter, listener?): Promise<null | ChannelStateChange>
Registers a listener for messages on this channel that match the supplied filter. The filter is used to provide server-side filtering of messages as part of filtered subscriptions.
Parameters
- event
- The event name to subscribe toType:
String
- events
- An array of event names to subscribe toType:
String[]
- listener
- is a function of the form
function(message)
to be called for each message - filter
- a filter object that is used to provide server-side filtering of messages as part of filtered subscriptionsType:
Object
Returns
Returns a promise. On successful channel attachment, the promise is fulfilled with a ChannelStateChange object. If the channel was already attached, then the promised will resolve with null
. 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 callingsubscribe
will implicitly attach the channel. However, regardless of the implicit attach outcome, the listener will still be registered - Calling subscribe with an event name is a convenient way to subscribe only to messages matching that event name. But this is purely a client-side filter, for convenience. It has no effect on what messages are actually sent by the server to the client. All clients attached to a given channel receive every message sent on that channel (that their capabilities allow them to receive); the channel is the unit of distribution. To filter messages server-side, you need to use filtered subscriptions and provide a
filter
when callingsubscribe()
. - If
subscribe
is called more than once with the same listener, then duplicates will be registered. For example, if yousubscribe
twice with the same listener and a message is later received, the same listener will be invoked twice - The registered listener remains active on the channel regardless of the current channel state. For example, if you call
subscribe
when a channel isattached
and it later becomesdetached
or evenfailed
, when the channel is reattached and a message is received, the listeners originally registered will still be invoked. Listeners are only removed when callingunsubscribe
or when a channel isreleased
using theRealtime.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 seven overloaded versions of this method:
unsubscribe(String event, listener)
Unsubscribe the given listener for the specified event name. This removes an earlier event-specific subscription.
unsubscribe(listener)
Unsubscribe the given listener (for any/all event names). This removes an earlier subscription.
unsubscribe(String[] events, listener)
Unsubscribe the given listener from all event names in the array.
unsubscribe(String event)
Unsubscribe all listeners for a given event name.
unsubscribe(String[] events)
Unsubscribe all listeners for all event names in the array.
unsubscribe(filter, listener?)
Unsubscribe all listeners for a given filter.
unsubscribe()
Unsubscribes all listeners to messages on this channel. This removes all earlier subscriptions.
Parameters
- event
- The event name to unsubscribe fromType:
String
- events
- An array of event names to unsubscribe fromType:
String[]
- listener
- is the callback listener function that was previously subscribed
history
history(Object params?): Promise<PaginatedResult<Message>>
Gets a paginated set of historical messages for this channel. If the channel is configured to persist messages to disk, then message history will typically be available for 24 – 72 hours. If not, messages are only retained in memory by the Ably service for two minutes.
Parameters
- params
- an optional object containing the query parameters, as specified in the message history API documentationType:
Object
Further details of the supported options
params, see message history API documentation.
Returns
Returns a promise. On success, the promise is fulfilled with a PaginatedResult object containing an array of messages. On failure, the promise is rejected with an ErrorInfo
object that details the reason why it was rejected.
setOptions
setOptions(options): Promise<void>
Set the ChannelOptions for the channel.
Parameters
- options
- The options to set for the channelType:
ChannelOptions
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.
attach
attach(): Promise<null | ChannelStateChange>
Attach to this channel ensuring the channel is created in the Ably system and all messages published on the channel will be received by any channel listeners registered using subscribe()
. Any resulting channel state change will be emitted to any listeners registered using the on
or once
methods.
As a convenience, attach()
will be called implicitly if subscribe()
for the Channel
is called, or enter()
or subscribe()
is called on the Presence
for this Channel
.
Returns
Returns a promise. On successful attachment, the promise is fulfilled with a ChannelStateChange object. If the channel was already attached, then the promised is fulfilled with null
. On failure, the promise is rejected with an ErrorInfo
object that details the reason why it was rejected.
detach
detach(): Promise<void>
Detach from this channel. Any resulting channel state change will be emitted to any listeners registered using the on
or once
methods.
Please note: Once all clients globally have detached from the channel, the channel will be released in the Ably service within two minutes.
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.
on
There are three overloaded versions of this method:
on(String event, listener(ChannelStateChange stateChange))
Register the given listener for the specified ChannelEvent on the Channel
.
The listener is passed a ChannelStateChange object that contains the current state, previous state, a boolean indicating whether the channel was resumed, and an optional reason for the state change.
on(String[] events, listener(ChannelStateChange stateChange))
Same as above, but registers multiple listeners, one for each event in the array.
on(listener(ChannelStateChange stateChange))
Register the given listener for all ChannelEvents on the Channel
.
The listener is passed a ChannelStateChange object that contains the current state, previous state, the event, a boolean indicating whether the channel was resumed, and an optional reason for the state change.
If an exception is thrown in the 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
Parameters
- event(s)
- the channel event(s) to subscribe to, see ChannelEvent for supported channel eventsType:
String
orString[]
- listener
- is a function of the form
function(stateChange)
to be notified for matching event changes.
once
There are two overloaded versions of this method:
once(String event, listener(ChannelStateChange stateChange))
Register the given listener for a single occurrence of the specified ChannelEvent on the Channel
. Once the listener has been called, it is removed as a registered listener and will not be called again.
The listener is passed a ChannelStateChange object that contains the current state, previous state, the event, a boolean indicating whether the channel was resumed, and an optional reason for the event change.
once(listener(ChannelStateChange stateChange))
Register the given listener for a single occurrence of any ChannelEvent on the Channel
. Once the listener has been called, it is removed as a registered listener and will not be called again.
The listener is passed a ChannelStateChange object that contains the current state, previous state, the event, a boolean indicating whether the channel was resumed, and an optional reason for the event change.
If an exception is thrown in the 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
Parameters
- event
- the channel event to subscribe to, see ChannelEvent for supported channel eventsType:
String
- listener
- is a function of the form
function()
to be notified for a single occurrence of a matching event change. The current event is available asthis.event
off
There are six overloaded versions of this method:
off(String event, listener)
Remove the given listener for the ChannelEvent.
off(listener)
Remove the given listener for all ChannelEvents.
off(String[] events, listener)
Removes the given listener from all ChannelEvents in the array.
off(String event)
Removes all listeners for a given ChannelEvent
.
off(String[] events)
Removes all listeners for all ChannelEvents in the array.
off()
Removes all listeners (including both those registered against specific events and those registered without an event).
Parameters
- event(s)
- the channel event(s) to unsubscribe fromType:
String
orString[]
- listener
- is the listener function to be removed
whenState
whenState(targetState): Promise<null | ChannelStateChange>
Checks if a channel is in a given state and returns null
if it is, else calls once()
for the given state.
Parameters
- targetState
- The
ChannelState
to wait forType:ChannelState
Returns
Returns a promise. If the channel is already in the given state, the promise will immediately resolve to null
. If not, it will call once()
to return a promise which resolves the next time the channel transitions to the given state.
Related types
ChannelState
ChannelState
is a String with a value matching any of the Realtime Channel
states.
var ChannelStates = [
'initialized',
'attaching',
'attached',
'detaching',
'detached',
'failed',
'suspended'
]
CopyCopied!
ChannelEvent
ChannelEvent
is a String that can be emitted as an event on the Channel
object; either a ChannelState
or an update
event.
var ChannelEvents = [
'initialized',
'attaching',
'attached',
'detaching',
'detached',
'failed',
'suspended',
'update'
]
CopyCopied!
ChannelStateChange
A ChannelStateChange is a type encapsulating state change information emitted by the Channel
object. See Channel#on
to register a listener for one or more events.
Attributes
- current
- the new current stateType:
ChannelState
- previous
- the previous state. (for the
update
event, this will be equal to thecurrent
state)Type:ChannelState
- event
- the event that triggered this state changeType:
ChannelEvent
- reason
- an
ErrorInfo
containing any information relating to the transitionType:ErrorInfo
- resumed
- a boolean indicated whether message continuity on this channel is preserved, see Nonfatal channel errors for more info.Type: Boolean
Message
A Message
represents an individual message that is sent to or received from Ably.
name
The event name, if provided. Type: String
data
The message payload, if provided.Type: String
, StringBuffer
, JSON Object
extras
Metadata and/or ancillary payloads, if provided. Valid payloads include push
, headers
(a map of strings to strings for arbitrary customer-supplied metadata), ephemeral
, and privileged
objects.Type: JSON Object
id
A Unique ID assigned by Ably to this message.Type: String
clientId
The client ID of the publisher of this message.Type: String
connectionId
The connection ID of the publisher of this message.Type: String
connectionKey
A connection key, which can optionally be included for a REST publish as part of the publishing on behalf of a realtime client functionalityType: String
timestamp
Timestamp when the message was received by the Ably, as milliseconds since the epoch.Type: Integer
encoding
This will typically be empty as all messages 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
payload.Type: String
action
The action type of the message, one of the MessageAction
enum values.Type: int enum { MESSAGE_CREATE, MESSAGE_UPDATE, MESSAGE_DELETE, META, MESSAGE_SUMMARY }
serial
This message’s unique serial (an identifier that will be the same in all future updates of this message).Type: String
refSerial
If this message references another, the serial of that message.Type: String
refType
If this message references another, the type of reference that is.Type: String
createdAt
The timestamp of the very first version of a given message (will differ from timestamp
only if the message has been updated or deleted).Type: Integer
version
The version of the message, lexicographically-comparable with other versions (that share the same serial). Will differ from the serial only if the message has been updated or deleted.Type: String
operation
In the case of an updated or deleted message, this will contain metadata about the update or delete operation.Type: Operation
Message constructors
Message.fromEncoded
Message.fromEncoded(Object encodedMsg, ChannelOptions channelOptions?) → Message
A static factory method to create a Message
from a deserialized Message
-like object encoded using Ably’s wire protocol.
Parameters
- encodedMsg
- a
Message
-like deserialized object.Type:Object
- channelOptions
- an optional
ChannelOptions
. If you have an encrypted channel, use this to allow the library can decrypt the data.Type:Object
Returns
A Message
object
Message.fromEncodedArray
Message.fromEncodedArray(Object[] encodedMsgs, ChannelOptions channelOptions?) → Message[]
A static factory method to create an array of Messages
from an array of deserialized Message
-like object encoded using Ably’s wire protocol.
Parameters
- encodedMsgs
- an array of
Message
-like deserialized objects.Type:Array
- channelOptions
- an optional
ChannelOptions
. If you have an encrypted channel, use this to allow the library can decrypt the data.Type:Object
Returns
An Array
of Message
objects
ChannelOptions Object
Channel options are used for setting channel parameters and configuring encryption.
ChannelOptions
, a plain JavaScript object, may optionally be specified when instancing a Channel
, and this may be used to specify channel-specific options. The following attributes can be defined on the object:
Properties
- params
- Optional parameters which specify behaviour of the channel.Type:
JSON Object
- cipher
- Requests encryption for this channel when not null, and specifies encryption-related parameters (such as algorithm, chaining mode, key length and key). See an exampleType:
CipherParams
or an options object containing at a minimum akey
DeriveOptions
Properties passed to getDerived()
to filter the messages returned in a subscription to it.
Parameters
- filter
- The filter expression to use when creating or returning the derived channel. This is a JMESPath queryType:
String
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
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
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());
CopyCopied!