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:

Parameters
ParameterDescriptionType
datadata 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
messageA message object to publishMessage
messagesAn array of message objects to publishMessage []
&blockyields 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

Subscribe a single listener to messages on this channel for multiple event name values.
Parameters
ParameterDescriptionType
nameThe event name to subscribe toString
namesAn argument array of event names to subscribe to*argument
&blockyields 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 calling subscribe will 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 filter when calling subscribe().
  • If subscribe is called more than once with the same block, then duplicates will be registered. For example, if you subscribe twice 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 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 blocks 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

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
ParameterDescriptionType
nameThe event name to unsubscribe fromString
&listener_blockpreviously 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
ParameterDescriptionType
optionsan optional set of key value pairs containing the query parameters, as specified in the message history API documentationHash
&blockyields 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
ParameterDescriptionType
&blockyields 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
ParameterDescriptionType
&blockyields 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
ParameterDescriptionType
eventthe channel event as a Symbol such as :attached or a ChannelEvent object to subscribe toChannelEvent
&blocklistener 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
ParameterDescriptionType
eventthe channel event as a Symbol such as :attached or a ChannelEvent object to subscribe toChannelEvent
&blocklistener 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
ParameterDescriptionType
eventthe channel event as a Symbol such as :detached or a ChannelEvent object to unsubscribe fromChannelEvent
&blockis the listener block to be removed-

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

Ruby

1

2

3

4

5

6

:initialized # => 0
:attaching # =>   1
:attached # =>    2
:detaching # =>   3
:detached # =>    4
:failed # =>      5

Constant states

Ruby

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 # =>      5

Example usage

Ruby

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 # => true

Channel::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

Ruby

1

2

3

4

5

6

7

:initialized # => 0
:attaching # =>   1
:attached # =>    2
:detaching # =>   3
:detached # =>    4
:failed # =>      5
:update # =>      6

Constant states

Ruby

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 # =>      6

ChannelStateChange

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

AttributeDescriptionType
currentthe new current stateChannel::STATE
previousthe previous state. (for the update event, this will be equal to the current state)Channel::STATE
eventthe event that triggered this state changeChannel::EVENT
reasonan ErrorInfo containing any information relating to the transitionErrorInfo
resumeda 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
ParameterDescriptionType
encodedMsga Message-like deserialized objectObject
channelOptionsan optional ChannelOptions. If you have an encrypted channel, use this to allow the library to decrypt the dataObject
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
ParameterDescriptionType
encodedMsgsan array of Message-like deserialized objectsArray
channelOptionsan optional ChannelOptions. If you have an encrypted channel, use this to allow the library to decrypt the dataObject
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

PropertyDescriptionType
:cipherRequests encryption for this channel when not null, and specifies encryption-related parameters (such as algorithm, chaining mode, key length and key). See an exampleCipherParams 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

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

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

Ruby

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