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 all SDK-held references to a Channel object, enabling it to be garbage collected. It can be useful for applications that work with a continually changing set of channels on a single client and need to avoid unbounded memory growth; if this does not describe your application, don't call it.
This method only affects the local client-side representation of the channel. The channel itself on the Ably platform is not deleted or changed, and other client instances (in the same or different processes) are unaffected.
Channels not already in the initialized, detached, or failed state are detached before release. After release, calling channels.get(channelName) returns a fresh channel object in the initialized state.
Channel
The Channel object, created via the Channels object, is used to interact with a specific channel.
Ably::Realtime::Channel Attributes
The Channel object exposes the following public attributes:
state
The current Ably::Realtime::Channel::STATE state of this Channel. See the supported channel states for more information.
error_reason
When a channel failure occurs this attribute is populated.
The type is AblyException.
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.
Channel Methods
publish
There are two overloaded versions of this method:
Deferrable publish(String name, Object data) -> yields
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 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.
Deferrable publish(Message[] messages) -> yields
Publish several messages on this channel. A block may optionally be passed in to this call to be notified of success 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:
- 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
| Parameter | Description | Type |
|---|---|---|
| data | data payload for the message. The supported payload types are Strings, Hash or Array objects that can be serialized to JSON using to_json, binary data as ASCII-8BIT byte arrays, and null. (Note that if sending a byte array, it should be the entire payload; a hash or array with a bytearray field within it may not be correctly encoded) | Object |
| message | A message object to publish | Message |
| messages | An array of message objects to publish | Message [] |
| &block | yields upon successfully publishing the message | - |
Returns
A Deferrable object is returned from the method.
On successful publish of the message, the registered success blocks for the Deferrable and any block provided to the method are executed. On failure to publish the message, the errback callbacks of the Deferrable are called with an ErrorInfo argument describing the failure reason.
subscribe
There are overloaded versions of this method:
subscribe → yields Message
Subscribe to messages on this channel. The caller supplies a block, which is called each time one or more messages arrives on the channel.
subscribe(String name) → yields Message
Subscribe to messages with a given event name on this channel. The caller supplies a block, which is called each time one or more matching messages arrives on the channel.
subscribe(String *names) → yields Message
name values.
Parameters
| Parameter | Description | Type |
|---|---|---|
| name | The event name to subscribe to | String |
| names | An argument array of event names to subscribe to | *argument |
| &block | yields each matching message when received on the channel | - |
Considerations
- If the channel is
initialized(i.e. no attempt to attach has yet been made for this channel), then callingsubscribewill implicitly attach the channel. However, regardless of the implicit attach outcome, the block 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
filterwhen callingsubscribe(). - If
subscribeis called more than once with the same block, then duplicates will be registered. For example, if yousubscribetwice with the same block and a message is later received, the same block will be invoked twice - The registered block remains active on the channel regardless of the current channel state. For example, if you call
subscribewhen a channel isattachedand it later becomesdetachedor evenfailed, when the channel is reattached and a message is received, the blocks originally registered will still be invoked. Listeners are only removed when callingunsubscribeor when a channel isreleasedusing 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
errorlevel, so as not to affect other listeners for the same event
unsubscribe
There are three overloaded versions of this method:
unsubscribe(String name, &listener_proc)
Unsubscribe the given listener for the specified event name. This removes an earlier event-specific subscription.
unsubscribe(&listener_proc)
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
| Parameter | Description | Type |
|---|---|---|
| name | The event name to unsubscribe from | String |
| &listener_block | previously registered listener block | - |
history
Deferrable history(Hash options) -> yields 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
| Parameter | Description | Type |
|---|---|---|
| options | an optional set of key value pairs containing the query parameters, as specified in the message history API documentation | Hash |
| &block | yields a PaginatedResult<Message> object | - |
Further details of the supported options params, see message history API documentation.
Returns
A Deferrable object is returned from the method.
On success, the registered success blocks for the Deferrable and any block provided to the method yield a PaginatedResult that encapsulates an array of Message objects corresponding to the current page of results. PaginatedResult supports pagination using next() and first() methods.
Failure to retrieve the message history will trigger the errback callbacks of the Deferrable with an ErrorInfo object with the failure reason.
attach
Deferrable attach -> yields
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
| Parameter | Description | Type |
|---|---|---|
| &block | yields once the channel becomes attached | - |
Returns
A Deferrable object is returned from the attach method.
On successful attachment, the success callbacks for the Deferrable are called and any block provided to the method is yielded. Failure to attach will trigger the errback callbacks of the Deferrable with an ErrorInfo object with the failure reason.
detach
Deferrable detach -> yields
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
| Parameter | Description | Type |
|---|---|---|
| &block | yields once the channel becomes detached | - |
Returns
A Deferrable object is returned from the detach method.
On successful detachment, the registered success blocks for the Deferrable and any block provided to the method are executed. Failure to detach will trigger the errback callbacks of the Deferrable with an ErrorInfo object with the failure reason.
on
There are two overloaded versions of this method:
on(ChannelEvent *event) -> yields ChannelStateChange
Register the given listener block 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 -> yields ChannelStateChange
Register the given listener block 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
| Parameter | Description | Type |
|---|---|---|
| event | the channel event as a Symbol such as :attached or a ChannelEvent object to subscribe to | ChannelEvent |
| &block | listener block that is yielded to for matching event changes | - |
once
There are two overloaded versions of this method:
once(ChannelEvent *event) -> yields ChannelStateChange
Register the given listener block 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 -> yields ChannelStateChange
Register the given listener block 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
| Parameter | Description | Type |
|---|---|---|
| event | the channel event as a Symbol such as :attached or a ChannelEvent object to subscribe to | ChannelEvent |
| &block | listener block that is yielded to for a single occurrence of a matching event change | - |
off
There are two overloaded versions of this method:
off(ChannelEvent *event, &block)
Remove the given listener block for the ChannelEvent.
off(&block)
Remove the given listener block for all ChannelEvents.
Parameters
| Parameter | Description | Type |
|---|---|---|
| event | the channel event as a Symbol such as :detached or a ChannelEvent object to unsubscribe from | ChannelEvent |
| &block | is the listener block to be removed | - |
Related types
Channel::STATE Enum
Ably::Realtime::Channel::STATE is an enum-like value representing all the Realtime Channel states. STATE can be represented interchangeably as either symbols or constants.
Symbol states
1
2
3
4
5
6
:initialized # => 0
:attaching # => 1
:attached # => 2
:detaching # => 3
:detached # => 4
:failed # => 5Constant states
1
2
3
4
5
6
Channel::STATE.Initialized # => 0
Channel::STATE.Attaching # => 1
Channel::STATE.Attached # => 2
Channel::STATE.Detaching # => 3
Channel::STATE.Detached # => 4
Channel::STATE.Failed # => 5Example usage
1
2
3
4
5
6
7
8
# Example with symbols
channel.on(:attached) { ... }
# Example with constants
channel.on(Ably::Realtime::Channel::STATE.Attached) { ... }
# Interchangeable
Ably::Realtime::Channel::STATE.Attached == :attached # => trueChannel::EVENT Enum
Ably::Realtime::Channel::EVENT is an enum-like value representing all the events that can be emitted be the Channel; either a ChannelState or an :update event. EVENT can be represented interchangeably as either symbols or constants.
Symbol states
1
2
3
4
5
6
7
:initialized # => 0
:attaching # => 1
:attached # => 2
:detaching # => 3
:detached # => 4
:failed # => 5
:update # => 6Constant states
1
2
3
4
5
6
7
Channel::EVENT.Initialized # => 0
Channel::EVENT.Attaching # => 1
Channel::EVENT.Attached # => 2
Channel::EVENT.Detaching # => 3
Channel::EVENT.Detached # => 4
Channel::EVENT.Failed # => 5
Channel::EVENT.Update # => 6ChannelStateChange
A Ably::Models::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
| Attribute | Description | Type |
|---|---|---|
| current | the new current state | Channel::STATE |
| previous | the previous state. (for the update event, this will be equal to the current state) | Channel::STATE |
| event | the event that triggered this state change | Channel::EVENT |
| reason | an ErrorInfo containing any information relating to the transition | ErrorInfo |
| resumed | a boolean indicated whether message continuity on this channel is preserved, see Nonfatal channel errors for more info. | Boolean |
Ably::Models::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, Binary (ASCII-8BIT String), Hash, Array
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: Hash, Array
id
A Unique ID assigned by Ably to this message.
Type: String
client_id
The client ID of the publisher of this message.
Type: String
connection_id
The connection ID of the publisher of this message.
Type: String
connection_key
A connection key, which can optionally be included for a REST publish as part of the publishing on behalf of a realtime client functionality.
Type: String
timestamp
Timestamp when the message was first received by the Ably, as a Time object.
Type: Time
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
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
| Parameter | Description | Type |
|---|---|---|
| encodedMsg | a Message-like deserialized object | Object |
| channelOptions | an optional ChannelOptions. If you have an encrypted channel, use this to allow the library to decrypt the data | 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
| Parameter | Description | Type |
|---|---|---|
| encodedMsgs | an array of Message-like deserialized objects | Array |
| channelOptions | an optional ChannelOptions. If you have an encrypted channel, use this to allow the library to decrypt the data | Object |
Returns
An Array of Message objects
ChannelOptions Hash
Channel options are used for configuring encryption.
ChannelOptions, a Hash object, may optionally be specified when instancing a Channel, and this may be used to specify channel-specific options. The following key symbol values can be added to the Hash:
Attributes
| Property | Description | Type |
|---|---|---|
| :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 example | CipherParams or an options hash containing at a minimum a key |
Ably::Models::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.
Attributes
| Property | Description | Type |
|---|---|---|
| items | contains 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
PaginatedResult first
Returns a new PaginatedResult for the first page of results. When using the Realtime library, the first method returns a Deferrable and yields a PaginatedResult.
has_next?
Boolean has_next?
Returns true if there are more pages available by calling next and returns false if this page is the last page available.
last?
Boolean last?
Returns true if this page is the last page and returns false if there are more pages available by calling next available.
next
PaginatedResult next
Returns a new PaginatedResult loaded with the next page of results. If there are no further pages, then null is returned. When using the Realtime library, the first method returns a Deferrable and yields a PaginatedResult.
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# When using the REST sync library
first_page = channel.history
puts "Page 0 item 0: #{first_page.items[0].data}"
if first_page.has_next?
next_page = first_page.next
puts "Page 1 item 1: #{next_page.items[1].data}"
puts "Last page?: #{next_page.is_last?}"
end
# When using the Realtime EventMachine library
channel.history do |first_page|
puts "Page 0 item 0: #{first_page.items[0].data}"
if first_page.has_next?
first_page.next do |next_page|
puts "Page 1 item 1: #{next_page.items[1].data}"
puts "Last page?: #{next_page.is_last?}"
end
end
end