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 channelName, ChannelOptions channelOptions)
Creates a new Channel object if none for the channel exists, or returns the existing channel object.
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.
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 attribute 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.
Methods
publish
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. 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
- name
- event name for the published messageType:
String
- message
- A message object to publishType:
Message
- messages
- An array of message objects to publishType:
Message []
subscribe
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[]
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 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 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 three 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()
Unsubscribes all listeners to messages on this channel. This removes all earlier subscriptions.
Parameters
- name
- The event name to unsubscribe fromType:
String
history
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
Further details of the supported options
params, see message history API documentation.
attach
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
detach
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
on
There are two 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(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
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
off
There are two 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.
Parameters
Related types
ChannelState
ChannelEvent
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.
Properties
- name
- Event name, if providedType:
String
- data
- The presence update payload, if providedType:
- extras
- Metadata and/or ancillary payloads, if provided. The only currently valid payloads for extras are the
push
,ref
andprivileged
objects.Type: - 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 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 configuring encryption.
Properties
- 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
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
- items
- contains the current page of results (for example an Array of
Message
orPresenceMessage
objects for a channel history request)Type:Array <Message, Presence, Stats>
Methods
first
first(callback(ErrorInfo err, PaginatedResult resultPage))
Returns a new PaginatedResult
for the first page of results.
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(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.
Example
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());
});
});
CopyCopied!