API Reference

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

getGet

Channel get(String channelName, ChannelOptions channelOptions)Channel Get(String channelName, ChannelOptions channelOptions)ARTRealtimeChannel get(String channelName, ARTChannelOptions channelOptions);

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

releaseRelease

release(String channelName)void release(String channelName)bool 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 PropertiesARTRealtimeChannel PropertiesAbly::Realtime::Channel Attributesio.ably.lib.realtime.Channel MembersIO.Ably.Realtime.RealtimeChannel Properties

The Channel object exposes the following public propertiesattributesmembers:

stateState

The current io.ably.lib.realtime.ChannelState stateIO.Ably.Realtime.ChannelState stateAbly::Realtime::Channel::STATE stateARTRealtimeChannelStateChannelState of this Channel. See the supported channel states for more information.

errorReasonreasonerror_reasonErrorReason

When a channel failure occurs this attributememberpropertyproperty is populated.
The type is ErrorInfoAblyException.

nameName

The name String unique to this channel.

presencePresence

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

publishPublish

There are two overloaded versions of this method:

publish(String name, Object data, callback(ErrorInfo err))Deferrable publish(String name, Object data) → yieldsvoid publish(String name, Object data, CompletionListener listener)void Publish(string name, object data, Action<bool, ErrorInfo> callback = null, string clientId = null)publish(name: String?, data: AnyObject?, callback: ((ARTErrorInfo?) → Void)?)Future publish(name: String name, data: Object data, message: Message message)

Publish a single message on this channel based on a given event name and payload. A callbacklistener 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))Deferrable publish(Message[] messages) → yieldsvoid publish(Message[] messages, CompletionListener listener)void Publish(IEnumerable<Message> messages, Action<bool, ErrorInfo> callback = null)publish(messages: [ ARTMessage ], callback: ((ARTErrorInfo?) → Void)?)Future publish(messages: List<Message> messages)

Publish several messages on this channel. A callbacklistenerblock 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. When publish is called with this client library, it won’t attempt to implicitly attach to the channel.

Parameters

name
event name for the published message
Type: String
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
data
data payload for the message. The supported payload types are Strings, JsonObject, binary data as byte arrays, and null.
Type: Object
data
data payload for the message. The supported payload types are Strings, binary data as byte arrays, any plain c# class that can be serialized to Json, and null.
Type: Object
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)
Type: Object
data
data payload for the message. The supported payload types are NSString, NSDictionary or NSArray objects that can be serialized to JSON, binary data as NSData, and nil.
Type: Object
data
data payload for the message. The supported payload types are String, Map, List, and null.
Type: Object
message
A message object to publish
Type: Message
messages
An array of message objects to publish
Type: Message []
callback
is a function of the form function(err) which is called upon completion
listener
Listener to be notified on completion
Type: CompletionListener
callback
is an action of the form Action<bool, ErrorInfo> which is called upon completion
&block
yields upon successfully publishing the message
callback
called upon publishing the message, or with an error

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.

Callback result

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

Listener result

On successful publish of the message, the onSuccess method of the CompletionListener is called. On failure to publish the message, the onError method is called with an ErrorInfo argument describing the failure reason.

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.

Returns

Future<void>

On successful publish of the message, no exception will be thrown. On failure to publish the message, an AblyException will be thrown with an `errorInfo` property describing the failure reason.

subscribeSubscribe

There are overloaded versions of this method:

subscribe(listener(Message))void subscribe(MessageListener listener)void Subscribe(Action<Message> handler)subscribe → yields Messagesubscribe(callback: (ARTMessage) → Void) → ARTEventListener?StreamSubscription<ably.Message> subscribe().listen((ably.Message) → void)

Subscribe to messages on this channel. The caller supplies a listener functiona lambda expressionan implementation of the MessageListener interfacea block, which is called each time one or more messages arrives on the channel.

subscribe(String name, listener(Message))void subscribe(String name, MessageListener listener)void Subscribe(string name, Action<Message> handler)subscribe(String name) → yields Messagesubscribe(name: String, callback: (ARTMessage) → Void) → ARTEventListener?StreamSubscription<ably.Message> subscribe(name: String).listen((ably.Message) → void)

Subscribe to messages with a given event name on this channel. The caller supplies a listener functiona lambda expressionan implementation of the MessageListener interfacea block, which is called each time one or more matching messages arrives on the channel.

subscribe(String[] names, listener(Message))void subscribe(String[] names, MessageListener listener)subscribe(String *names) → yields MessageStreamSubscription<ably.Message> subscribe(names: List).listen((ably.Message) → void)

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

Parameters

name
The event name to subscribe to
Type: String
names
An argument array of event names to subscribe to
Type: String[] *argument
listener
is a function of the form function(message) to be called for each message
MessageListener listener
Message listener to be notified for matching messages
&block
yields each matching message when received on the channel
callback
called with each matching message when received on the channel
handler
called with 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 listenerblockhandler 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 listenerblockhandler, then duplicates will be registered. For example, if you subscribe twice with the same listenerblockhandler and a message is later received, the same listenerblockhandler will be invoked twice
  • The registered listenerblockhandler 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 listenersblockshandlers originally registered will still be invoked. Listeners are only removed when calling unsubscribestreamSubscription.close or when a channel is released using the Realtime.channels.release(name)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
unsubscribeUnsubscribe

There are sixthree overloaded versions of this method:

unsubscribe(String name, listener)void unsubscribe(String name, MessageListener listener)bool Unsubscribe(string eventName, Action<Message> handler)unsubscribe(String name, &listener_proc)unsubscribe(name: String, listener: ARTEventListener)

Unsubscribe the given listener for the specified event name. This removes an earlier event-specific subscription.

unsubscribe(listener)void unsubscribe(MessageListener listener)bool Unsubscribe(Action<Message> handler)unsubscribe(&listener_proc)unsubscribe(listener: ARTEventListener)

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()void unsubscribe()void Unsubscribe()unsubscribe()

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

Parameters

name
The event name to unsubscribe from
Type: String
names
An array of event names to unsubscribe from
Type: String[]
listener
is the callback listener function that was previously subscribed
listener
previously registered listener
Type: MessageListener
&listener_block
previously registered listener block
listener
previous return value from a subscribe call
handler
is the lambda expression that was previously subscribed

streamSubscription obtained from a subscription can be used to cancel a listener by calling streamSubscription.cancel.
historyHistory

history(Object options, callback(ErrorInfo err, PaginatedResult<Message> resultPage))Deferrable history(Hash options) → yields PaginatedResult<Message>PaginatedResult<Message> history(Param [] options)Task<PaginatedResult> HistoryAsync(PaginatedRequestParams dataQuery, bool untilAttach = false)history(query: ARTRealtimeHistoryQuery?, callback: (ARTPaginatedResult<ARTMessage>?, ARTErrorInfo?) → Void) throws

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

optionsquerydataQuery
an optional object containing the query parametersan optional set of key value pairs containing the query parameters, as specified in the message history API documentation.
Type: ObjectARTRealtimeHistoryQueryPaginatedRequestParamsHashParam []
callback
is a function of the form: function(err, resultPage)
&block
yields a PaginatedResult<Message> object
callback
called with a ARTPaginatedResult<ARTMessage> object or an error

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.

Returns

On success, the returned PaginatedResult 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 raise an AblyException

Returns

The return value is Task<PaginatedResult<Message>> which needs to be awaited.

On success, the returned PaginatedResult encapsulates an array of Message objects corresponding to the current page of results. PaginatedResult supports pagination using NextAsync and FirstAsync methods.

Failure to retrieve the message history will raise an AblyException

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.

attachAttach

attach(callback(ErrorInfo err))void attach()void Attach(Action<TimeSpan, ErrorInfo?> callback = null)Deferrable attach → yieldsattach(callback: ((ARTErrorInfo?) → Void)?)Future attach()

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()Subscribe()subscribe. Any resulting channel state change will be emitted to any listeners registered using the onOn or onceOnce methods.

As a convenience, attach()Attach()attach will be called implicitly if subscribe()Subscribe()subscribe for the Channel is called, or enter()Enter()enter or subscribe()Subscribe()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
&block
yields once the channel becomes attached
callback
is a lambda expression of the form Action<TimeSpan, ErrorInfo> and is called once the channel attach succeeds or fails
callback
called once the channel becomes attached or if an error occurs

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.

Returns

Future<void>

Failure to attach will throw an AblyException with an errorInfo property with the failure reason.

detachDetach

detach(callback(ErrorInfo err))void detach()void Detach(Action<TimeSpan, ErrorInfo> callback = null)Deferrable detach → yieldsdetach(callback: ((ARTErrorInfo?) → Void)?)Future detach()

Detach from this channel. Any resulting channel state change will be emitted to any listeners registered using the onOn or onceOnce 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
callback
is a lambda expression in the form Action<TimeSpan, ErrorInfo> and is called once the channel detach succeeds or fails
&block
yields once the channel becomes detached
callback
called once the channel becomes detached or if an error occurs

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.

Returns

Future<void>

Failure to detach will throw an AblyException with an errorInfo property with the failure reason.

onOn

There are threetwo overloaded versions of this method:

on(String event, listener(ChannelStateChange stateChange))on(ChannelEvent *event) → yields ChannelStateChangevoid on(ChannelEvent event, ChannelStateListener listener)void On(ChannelEvent event, Action<ChannelStateChange> action)on(event: ARTChannelEvent, call: (ARTChannelStateChange?) → Void) → ARTEventListenerStream<ChannelEvent> on(ChannelEvent channelEvent)

The Stream returned can be subscribed for with a listener.

final streamSubscription = stream.listen(listener)

Register the given listener blockfunction for the specified ChannelEvent on the Channel.
The listener is passed a ChannelStateChangeARTChannelStateChange 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))on → yields ChannelStateChangevoid On(Action<ChannelStateChange> listener)void on(ChannelStateListener listener)on(call: (ARTChannelStateChange?) → Void) → ARTEventListenerStream<ChannelEvent> on()

The Stream returned can be subscribed for with a listener.

final streamSubscription = stream.listen(listener)

Register the given listener blockfunctionlambda expression for all ChannelEvents on the Channel.
The listener is passed a ChannelStateChangeARTChannelStateChange 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 events
Type: String or String[]
event
the channel event to subscribe to
Type: ChannelEvent
event
the channel event to subscribe to
Type: ChannelEvent
event
the channel event as a Symbol such as :attached or a ChannelEvent object to subscribe to
Type: ChannelEvent
event
the ARTChannelEvent to subscribe to
Type: ARTChannelEvent
event
the channel event to subscribe to
Type: ChannelEvent
listener
is a function of the form function(stateChange) to be notified for matching event changes.
listener
listener to be notified for matching event changes
Type: ChannelStateListener
action
lambda expression to be notified for matching event changes
Type: ChannelStateChange
&block
listener block that is yielded to for matching event changes
call
called possibly with an ErrorInfo

Example

Browser ChannelState change example

onceOnce

There are two overloaded versions of this method:

once(String event, listener(ChannelStateChange stateChange))once(ChannelEvent *event) → yields ChannelStateChangevoid once(ChannelEvent event, ChannelStateListener listener)void Once(ChannelEvent event, Action<ChannelStateChange> action)once(event: ARTChannelEvent, call: (ARTChannelStateChange?) → Void) → ARTEventListener

Register the given listener blockfunctionlambda expression 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 ChannelStateChangeARTChannelStateChange 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))once → yields ChannelStateChangevoid once(ChannelStateListener listener)void Once(Action<ChannelStateChange> listener)once(call: (ARTChannelStateChange?) → Void) → ARTEventListener

Register the given listener blockfunctionlambda expression 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 ChannelStateChangeARTChannelStateChange 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 events
Type: String
event
the channel event to subscribe to
Type: ChannelEvent
event
the channel event to subscribe to
Type: ChannelEvent
event
the channel event as a Symbol such as :attached or a ChannelEvent object to subscribe to
Type: ChannelEvent
event
the ARTChannelEvent to subscribe to
Type: ARTChannelEvent
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
listener
listener to be notified for a single occurrence of a matching event change
Type: ChannelStateListener
&block
listener block that is yielded to for a single occurrence of a matching event change
listener
listener lambda expression that is notified only once for a matching event change
call
called possibly with an ErrorInfo
offOff

There are sixtwo overloaded versions of this method:

off(String event, listener)off(ChannelEvent *event, &block)void off(ChannelEvent event, ChannelStateListener listener)void Off(ChannelEvent event, Action<ChannelStateChange> listener)off(event: ARTChannelEvent, listener: ARTEventListener)

Remove the given listener block for the ChannelEvent.

off(listener)off(&block)void off(ChannelStateListener listener)void Off(Action<ChannelStateChange> listener)off(listener: ARTEventListener)

Remove the given listener block 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 from
Type: String or String[]
event
the channel event to unsubscribe from
__Type: ChannelEvent-
event
the channel event to unsubscribe from
Type: ChannelEvent
event
the channel event as a Symbol such as :detached or a ChannelEvent object to unsubscribe from
Type: ChannelEvent
event
the ARTChannelEvent to unsubscribe from
Type: ARTChannelEvent
listener
is the listener function to be removed
listener
is the listener to be removed
Type: @ChannelStateListener
listener
is the listener function to be removed
&block
is the listener block to be removed
listener
previous return value from a on or once call
streamSubscription
obtained from calling on can be used to cancel a listener by calling streamSubscription.cancel

ChannelStateARTRealtimeChannelStateChannel::STATE Enumio.ably.lib.realtime.ChannelState EnumIO.Ably.Realtime.ChannelState Enumably.ChannelState Enum

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

var ChannelStates = [
  'initialized',
  'attaching',
  'attached',
  'detaching',
  'detached',
  'failed',
  'suspended'
]

io.ably.lib.realtime.ChannelState is an enum representing all the Realtime Channel states.

public enum ChannelState {
  initialized,  // 0
  attaching,    // 1
  attached,     // 2
  detaching,    // 3
  detached,     // 4
  failed        // 5
}

IO.Ably.Realtime.ChannelState is an enum representing all the Realtime Channel states.

public enum ChannelState
{
    Initialized = 0,
    Attaching = 1,
    Attached = 2,
    Detaching= 3,
    Detached = 4,
    Failed = 5
};

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

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

Constant states

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

# Example with symbols
channel.on(:attached) { ... }

# Example with constants
channel.on(Ably::Realtime::Channel::STATE.Attached) { ... }

# Interchangeable
Ably::Realtime::Channel::STATE.Attached == :attached # => true

ARTRealtimeChannelState is an enum representing all the Realtime Channel states.

typedef NS_ENUM(NSUInteger, ARTRealtimeChannelState) {
    ARTRealtimeChannelInitialized,
    ARTRealtimeChannelAttaching,
    ARTRealtimeChannelAttached,
    ARTRealtimeChannelDetaching,
    ARTRealtimeChannelDetached,
    ARTRealtimeChannelFailed
};
public enum ARTRealtimeChannelState : UInt {
    case Initialized
    case Attaching
    case Attached
    case Detaching
    case Detached
    case Failed
}

ChannelState is a string representing all the channel states

const (
  StateChanInitialized = 256
  StateChanConnecting = 512
  StateChanConnected = 1024
  StateChanDisconnected = 2048
  StateChanSuspended = 4096
  StateChanClosing = 8192
  StateChanClosed = 16384
  StateChanFailed = 32768
)

ably.ChannelState is an enum representing all the Realtime Channel states.

enum ChannelState {
  initialized,
  attaching,
  attached,
  detaching,
  detached,
  suspended,
  failed
}

ChannelEventARTChannelEventChannel::EVENT Enumio.ably.lib.realtime.ChannelEvent EnumIO.Ably.Realtime.ChannelEvent Enumably.ChannelEvent Enum

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'
]

io.ably.lib.realtime.ChannelEvent is an enum representing all the events that can be emitted be the Channel; either a ChannelState or an update event.

public enum ChannelEvent {
  initialized,  // 0
  attaching,    // 1
  attached,     // 2
  detaching,    // 3
  detached,     // 4
  failed        // 5
  update        // 6
}

IO.Ably.Realtime.ChannelEvent is an enum representing all the events that can be emitted be the Channel; either a ChannelState or an Update event.

public enum ChannelEvent
{
    Initialized = 0,
    Attaching = 1,
    Attached = 2,
    Detaching= 3,
    Detached = 4,
    Failed = 5,
    Update = 6
};

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

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

Constant states

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

ARTChannelEvent is the enum emitted as the event in ARTRealtimeChannel.on; either a ChannelState or an Update event.

typedef NS_ENUM(NSUInteger, ARTChannelEvent) {
    ARTChannelEventInitialized,
    ARTChannelEventAttaching,
    ARTChannelEventAttached,
    ARTChannelEventDetaching,
    ARTChannelEventDetached,
    ARTChannelEventFailed,
    ARTChannelEventUpdate
};
enum ARTChannelEvent : UInt {
    case Initialized
    case Attaching
    case Attached
    case Detaching
    case Detached
    case Failed
    case Update
}

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

const (
  StateChanInitialized = 256
  StateChanConnecting = 512
  StateChanConnected = 1024
  StateChanDisconnected = 2048
  StateChanSuspended = 4096
  StateChanClosing = 8192
  StateChanClosed = 16384
  StateChanFailed = 32768
)

ably.ChannelEvent is an enum representing all the events that can be emitted be the Channel; either a ChannelState or an update event.

enum ChannelEvent {
  initialized,
  attaching,
  attached,
  detaching,
  detached,
  suspended,
  failed,
  update
}

ChannelStateChangeARTRealtimeChannelStateChangeio.ably.lib.realtime.ChannelStateListener.ChannelStateChangeChannelStateChangeIO.Ably.Realtime.ChannelStateChangedably.ChannelStateChange

A Ably::Models::ChannelStateChangeChannelStateChangeARTRealtimeChannelStateChange 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

currentCurrent
the new current state
Type: ChannelStateChannel::[email protected]
previousPrevious
the previous state. (for the update event, this will be equal to the current state)
Type: ChannelStateChannel::[email protected]
eventEvent
the event that triggered this state change
Type: ChannelEventChannel::[email protected]
reasonReason
an ErrorInfo containing any information relating to the transition
Type: ErrorInfo
resumedResumed
a boolean indicated whether message continuity on this channel is preserved, see Nonfatal channel errors for more info.
Type: Boolean

MessageARTMessageAbly::Models::Messageio.ably.lib.types.MessageIO.Ably.Messageably.Message

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

PropertiesMembersAttributesAttributes

nameName
Event name, if provided
Type: String
dataData
The presence update payload, if provided
Type: String, ByteArray, JSONObject, JSONArrayString, byte[], plain C# object that can be converted to JsonString, []byteString, StringBuffer, JSON ObjectString, Binary (ASCII-8BIT String), Hash, ArrayString, Bytearray, Dict, ListString, NSData, Dictionary, ArrayNSString *, NSData *, NSDictionary *, NSArray *String, Binary String, Associative Array, ArrayObject
extrasExtras
Metadata and/or ancillary payloads, if provided. The only currently valid payload for extras is the push object.
Type: JSONObject, JSONArrayplain C# object that can be converted to JsonString, []byteJSON ObjectHash, ArrayDict, ListDictionary, ArrayNSDictionary *, NSArray *Associative Array, ArrayMap, List
idId
Unique ID assigned by Ably to this message. Can optionally be assigned by the client as part of idempotent publishing
Type: String
clientIdclient_idClientId
The client ID of the publisher of this message
Type: String
connectionIdconnection_idConnectionId
The connection ID of the publisher of this message
Type: String
timestampTimestamp
Timestamp when the message was received by the Ably service, as milliseconds since the epocha Time object
Type: IntegerLong IntegerDateTimeOffsetTimeNSDateDateTime
encodingEncoding
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

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 ObjectARTChannelOptionsChannelOptions Hashio.ably.lib.types.ChannelOptionsIO.Ably.Rest.ChannelOptionsably.ChannelOptions

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:

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:

ChannelOptions, an Associative Array, may optionally be specified when instancing a Channel, and this may be used to specify channel-specific options. The following named keys and values can be added to the Associated Array:

ARTio.ably.lib.types.ChannelOptions may optionally be specified when instancing a Channel, and this may be used to specify channel-specific options.

IO.Ably.ChannelOptions may optionally be specified when instancing a Channel, and this may be used to specify channel-specific options.

PropertiesMembersAttributes

:cipherCipherParamscipher
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
Type: CipherParams or an options objecta Param[] listan options hashan Associative Array containing at a minimum a key
paramsParams
Optional parameters which specify behaviour of the channel.
Type: Map<String, String>JSON Object
cipherCipherParams
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
Type: CipherParams or an options objecta Param[] listan options hashan Associative Array containing at a minimum a key

Static methods

withCipherKey

static ChannelOptions.withCipherKey(Byte[] or String key)

A helper method to generate a ChannelOptions for the simple case where you only specify a key.

Parameters

key
A binary Byte[] array or a base64-encoded String.

Returns

On success, the method returns a complete ChannelOptions object. Failure will raise an AblyException.

io.ably.lib.realtime.ChannelStateListener

A io.ably.lib.realtime.ChannelStateListener is an interface allowing a client to be notified of channel state changes for a Channel

public interface ChannelStateListener {
  // Called when the channel state changes
  public void onChannelStateChanged(ChannelStateChange stateChange, ErrorInfo reason);
}

io.ably.lib.realtime.CompletionListener

A io.ably.lib.realtime.CompletionListener is an interface allowing a client to be notified of the outcome of an asynchronous operation.

public interface CompletionListener {
  // Called when the associated operation completes successfully,
  public void onSuccess();

  // Called when the associated operation completes with an error.
  public void onError(ErrorInfo reason);
}

PaginatedRequestParams

HistoryRequestParams is a type that encapsulates the parameters for a history queries. For example usage see Channel#historyChannel#History.

Members

Start
null The start of the queried interval
Type: DateTimeOffset
End
null The end of the queried interval
Type: DateTimeOffset
Limit
null By default it is null. Limits the number of items returned by history or stats
Type: Integer
Direction
Backwards Enum which is either Forwards or Backwards
Type: Direction enum
ExtraParameters
Optionally any extra query parameters that may be passed to the query. This is mainly used internally by the library to manage paging.
Type: Dictionary<string, string>

io.ably.lib.realtime.Channel.MessageListener

A io.ably.lib.realtime.Channel.MessageListener is an interface allowing a client to be notified when messages are received on a channel using a channel subscription.

public interface MessageListener {
  // Called when one or more messages are received
  public void onMessage(Message message);
}

PaginatedResultARTPaginatedResultAbly::Models::PaginatedResultio.ably.lib.types.PaginatedResultIO.Ably.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.

PropertiesMembersAttributes

itemsItems
contains the current page of results (for example an Array of Message or PresenceMessage objects for a channel history request)
Type: Array <Message, Presence, Stats>Type: List <Message, Presence, Stats>

Methods

firstFirst

first(callback(ErrorInfo err, PaginatedResult resultPage))PaginatedResult firstPaginatedResult first()PaginatedResult first()Task<PaginatedResult> FirstAsync()PaginatedResult first()first(callback: (ARTPaginatedResult?, ARTErrorInfo?) → Void)First() (PaginatedResult, error)

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.The method is asynchronous and returns a Task which needs to be awaited to get the PaginatedResult.

hasNextHasNexthas_next?has_next

Boolean hasNext()Boolean has_next?Boolean hasNext()Boolean has_next()Boolean HasNext()Boolean hasNext()Boolean hasNext()HasNext() (bool)

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

isLastIsLastlast?is_last

Boolean isLast()Boolean last?Boolean isLast()Boolean is_last()Boolean IsLast()Boolean isLast()Boolean isLast()IsLast() (bool)

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

nextNext

next(callback(ErrorInfo err, PaginatedResult resultPage))PaginatedResult nextPaginatedResult next()PaginatedResult next()Task<PaginatedResult> NextAsync()PaginatedResult next()next(callback: (ARTPaginatedResult?, ARTErrorInfo?) → Void)Next() (PaginatedResult, error)

Returns a new PaginatedResult loaded with the next page of results. If there are no further pages, then nulla blank PaginatedResult will be returnedNullNonenil is returned. The method is asynchronous and return a Task which needs to be awaited to get the PaginatedResultWhen using the Realtime library, the first method returns a Deferrable and yields a PaginatedResult.

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());
  });
});
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());
  });
});
PaginatedResult firstPage = channel.history();
System.out.println("Page 0 item 0:" + firstPage.items[0].data);
if (firstPage.hasNext) {
  PaginatedResult nextPage = firstPage.next();
  System.out.println("Page 1 item 1:" + nextPage.items[1].data);
  System.out.println("More pages?:" + Strong.valueOf(nextPage.hasNext()));
};
PaginatedResult firstPage = channel.history();
System.out.println("Page 0 item 0:" + firstPage.items[0].data);
if (firstPage.hasNext) {
  PaginatedResult nextPage = firstPage.next();
  System.out.println("Page 1 item 1:" + nextPage.items[1].data);
  System.out.println("More pages?:" + Strong.valueOf(nextPage.hasNext()));
};
PaginatedResult<Message> firstPage = await channel.HistoryAsync(null);
Message firstMessage = firstPage.Items[0];
Console.WriteLine("Page 0 item 0: " + firstMessage.data);
if (firstPage.HasNext)
{
    var nextPage = await firstPage.NextAsync();
    Console.WriteLine("Page 1 item 1:" + nextPage.Items[1].data);
    Console.WriteLine("More pages?: " + nextPage.HasNext());
}
# 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
result_page = channel.history()
print 'Page 0 item 0: ' + str(result_page.items[0].data)
if result_page.has_next():
  next_page = result_page.next()
  print 'Page 1 item 1: ' + str(next_page.items[1].data)
  print 'Last page?: ' + str(next_page.is_last())
$firstPage = $channel.history();
echo("Page 0 item 0: " . $firstPage->items[0]->data);
if ($firstPage->hasNext()) {
  $nextPage = $firstPage->next();
  echo("Page 1 item 1: " . $nextPage->items[1]->data);
  echo("Last page?: " . $nextPage->isLast());
}
[channel history:^(ARTPaginatedResult<ARTMessage *> *paginatedResult, ARTErrorInfo *error) {
    NSLog(@"Page 0 item 0: %@", paginatedResult.items[0].data);
    [paginatedResult next:^(ARTPaginatedResult<ARTMessage *> *nextPage, ARTErrorInfo *error) {
        NSLog(@"Page 1 item 1: %@", nextPage.items[1].data);
        NSLog(@"Last page?: %d", nextPage.isLast());
    }];
}];
channel.history { paginatedResult, error in
    let paginatedResult = paginatedResult!
    print("Page 0 item 0: \((paginatedResult.items[0] as! ARTMessage).data)")
    paginatedResult.next { nextPage, error in
        let nextPage = nextPage!
        print("Page 1 item 1: \((nextPage.items[1] as! ARTMessage).data)")
        print("Last page? \(nextPage.isLast())")
    }
}
page0, err := channel.History(nil)
fmt.Println("Page. 0 item 0: %s\n", page0.Messages[0].Data)
page1, err := page0.Next()
fmt.Println("Page. 1 item 1: %s\n", page1.Messages[1].Data)
fmt.Println("Last page? %s\n", page1.IsLast())

io.ably.lib.types.Param

Param is a type encapsulating a key/value pair. This type is used frequently in method parameters allowing key/value pairs to be used more flexible, see Channel#history for an example.

Please note that key and value attributes are always strings. If an Integer or other value type is expected, then you must coerce that type into a String.

Members

key
The key value
Type: String
value
The value associated with the key
Type: String

Need help?

If you need any help with your implementation or if you have encountered any problems, do get in touch. You can also quickly find answers from our knowledge base, and blog.