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:

Channel get(String channelName, ChannelOptions channelOptions)

Creates a new Channel object if none for the channel exists, or returns the existing channel object.

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.

The Channel object, created via the Channels object, is used to interact with a specific channel.

The Channel object exposes the following public properties:

The current ChannelState of this Channel. See the supported channel states for more information.

When a channel failure occurs this property is populated.

The type is ErrorInfo.

The name String unique to this channel.

Provides access to the Presence object for this channel which can be used to access members present on the channel, or participate in presence.

Provides access to the PushChannel object for this channel which can be used to access members present on the channel, or participate in presence.

There are two overloaded versions of this method:

publish(String name, Object data, callback(ErrorInfo err))

Publish a single message on this channel based on a given event name and payload. A callback may optionally be passed in to this call to be notified of success or failure of the operation. 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, callback(ErrorInfo err))

Publish several messages on this channel. A callback may optionally be passed in to this call to be notified of success or failure of the operation. When publish is called with this client library, it won’t attempt to implicitly attach to the channel

The entire messages array is published atomically. This means that:

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 []
callback
is a function of the form function(err) which is called upon completion

Callback result

On successful publish of the message, err is null. On failure to publish the message, err contains an ErrorInfo object describing the failure reason.

There are overloaded versions of this method:

subscribe(listener(Message))

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 name, listener(Message))

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[] names, listener(Message))

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

Parameters

name
The event name to subscribe toType: String
names
An array of event names to subscribe toType: String[]
listener
is a function of the form function(message) to be called for each message

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
  • Calling subscribe with an event name is a convenient way to subscribe only to messages matching that event name. But this is purely a clientside 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.
  • 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 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 is attached and it later becomes detached or even failed, when the channel is reattached and a message is received, the listeners originally registered will still be invoked. Listeners are only removed when calling unsubscribe or when a 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

There are six overloaded versions of this method:

unsubscribe(String name, 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[] names, listener)

Unsubscribe the given listener from all event names in the array.

unsubscribe(String name)

Unsubscribe all listeners for a given event name.

unsubscribe(String[] names)

Unsubscribe all listeners for all event names in the array.

unsubscribe()

Unsubscribes all listeners to messages on this channel. This removes all earlier subscriptions.

Parameters

name
The event name to unsubscribe fromType: String
names
An array of event names to unsubscribe fromType: String[]
listener
is the callback listener function that was previously subscribed

history(Object options, callback(ErrorInfo err, PaginatedResult<Message> resultPage))

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

options
an optional object containing the query parameters, as specified in the message history API documentationType: Object
callback
is a function of the form: function(err, resultPage)

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

Callback result

On success, resultPage contains a PaginatedResult encapsulating an array of Message objects corresponding to the current page of results. PaginatedResult supports pagination using next() and first() methods.

On failure to retrieve message history, err contains an ErrorInfo object with the failure reason.

attach(callback(ErrorInfo err))

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.

Parameters

callback
is a function of the form function(err) and is called once the channel attach succeeds or fails

detach(callback(ErrorInfo err))

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.

Parameters

callback
is a function of the form function(err) and is called once the channel detach succeeds or fails

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 or String[]
listener
is a function of the form function(stateChange) to be notified for matching event changes.

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 as this.event

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 or String[]
listener
is the listener function to be removed

ChannelState is a String with a value matching any of the Realtime Channel states.

JavaScript v2.6
var ChannelStates = [ 'initialized', 'attaching', 'attached', 'detaching', 'detached', 'failed', 'suspended' ]
Copied!

ChannelEvent is a String that can be emitted as an event on the Channel object; either a ChannelState or an update event.

JavaScript v2.6
var ChannelEvents = [ 'initialized', 'attaching', 'attached', 'detaching', 'detached', 'failed', 'suspended', 'update' ]
Copied!

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 the current 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

A Message represents an individual message that is sent to or received from Ably.

Properties

name
Event name, if providedType: String
data
The presence update payload, if providedType: String, StringBuffer, JSON Object
extras
Metadata and/or ancillary payloads, if provided. The only currently valid payloads for extras are the push, ref and privileged objects.Type: JSON Object
id
Unique ID assigned by Ably to this message. Can optionally be assigned by the client as part of idempotent publishingType: String
clientId
The client ID of the publisher of this messageType: String
connectionId
The connection ID of the publisher of this messageType: String
timestamp
Timestamp when the message was received by the Ably service, as milliseconds since the epochType: 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 payloadType: String

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

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 a key

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(callback(ErrorInfo err, PaginatedResult resultPage))

Returns a new PaginatedResult for the first page of results.

Boolean hasNext()

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

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(callback(ErrorInfo err, PaginatedResult resultPage))

Returns a new PaginatedResult loaded with the next page of results. If there are no further pages, then null is returned.

JavaScript v2.6
channel.history(function(err, paginatedResult) { console.log('Page 0 item 0:' + paginatedResult.items[0].data); paginatedResult.next(function(err, nextPage) { console.log('Page 1 item 1: ' + nextPage.items[1].data); console.log('Last page?: ' + nextPage.isLast()); }); });
Copied!
Select...