Warning: You are viewing an old version (0.8) of this documentation. We recommend you view the latest version 1.2.
API Reference

Connection

Connection PropertiesARTConnection PropertiesAbly::Realtime::Connection Attributesio.ably.lib.realtime.Connection MembersIO.Ably.Realtime.Connection Properties

The Connection object exposes the following public propertiesattributesmembers:

idId

A unique public identifier String for this connection, used to identify this member in presence events and messages.

stateState

The current io.ably.lib.realtime.ConnectionState stateIO.Ably.Realtime.ConnectionState stateAbly::Realtime::Connection::STATE stateARTRealtimeConnectionState statestate String of this Connection. See the Connection states for more information.

errorReasonreasonErrorReasonerror_reason

When a connection failure occurs this attributememberproperty contains the ErrorInfoAblyException.

keyKey

A unique private connection key String used to recover or resume a connection, assigned by Ably. When recovering a connection explicitly, the recoveryKeyrecovery_key is used in the recover client options as it contains both the key and the last message serial.

This private connection key can also be used by other REST clients to publish on behalf of this client. See the publishing over REST on behalf of a realtime client documentation for more info.

recoveryKeyrecovery_keyRecoveryKey

The recovery key String can be used by another client to recover this connection’s state in the recoverRecover client options propertymemberattribute. See connection state recover options for more information.

serialSerial

The serial number Integer of the last message to be received on this connection, used automatically by the library when recovering or resuming a connection. When recovering a connection explicitly, the recoveryKeyrecovery_keyRecoveryKey is used in the recoverRecover client options as it contains both the key and the last message serial.

Connection MethodsARTConnection MethodsAbly::Realtime::Connection Methodsio.ably.lib.realtime.Connection MethodsIO.Ably.Realtime.Connection Methods

connectConnect

connect()Deferrable connect → yields Connectionvoid connect()void Connect()

Explicitly calling connectConnect is unnecessary unless the ClientOptions attribute autoConnectauto_connectAutoConnect is false. Unless already connected or connecting, this method causes the connection to open, entering the connecting state.

Returns

A Deferrable object is returned from this method.

On successfully connecting to Ably, the registered success blocks for the Deferrable and any block provided to this method yields a Connection object.

Failure to connect will trigger the errback callbacks of the Deferrable with an ErrorInfo object containing an error response as defined in the Ably REST API documentation.

closeClose

close()Deferrable close → yields Connectionvoid close()void Close()

Causes the connection to close, entering the closing state. Once closed, the library will not attempt to re-establish the connection without an explicit call to connect()Connect()connect":#connect.

Returns

A Deferrable object is returned from this method.

On successfully closing the connection, the registered success blocks for the Deferrable and any block provided to this method yields a Connection object.

Failure to close the connection will trigger the errback callbacks of the Deferrable with an ErrorInfo object containing an error response as defined in the Ably REST API documentation.

onOn

There are two overloaded versions of this method:

on(String state, listener(ConnectionStateChange stateChange))on(ConnectionState *state) → yields ConnectionStateChangevoid on(ConnectionState state, ConnectionStateListener listener)on(event: ARTRealtimeConnectionState, call: (ARTConnectionStateChange?) → Void) → ARTEventListenervoid On(ConnectionState event, Action<ConnectionStateChange> action)

Register the given listener blockfunctionaction for the specified ConnectionState statestate(s)stateevent changes on the Connection. The listener is passed a ConnectionStateChange object that contains the current state, previous state, and an optional reason for the state change.

on(listener(ConnectionStateChange stateChange))on → yields ConnectionStateChangevoid on(ConnectionStateListener listener)on(call: (ARTConnectionStateChange?) → Void) → ARTEventListenervoid On(Action<ConnectionStateChange> action)

Register the given listener blockfunctionaction for all ConnectionState changes on the Connection. The listener is passed a ConnectionStateChange object that contains the current state, previous state, and an optional reason for the state change.

Parameters

state
the connection state to subscribe to
Type: String
state
the connection state to subscribe to
Type: ConnectionState
event
the connection state to subscribe to
Type: ConnectionState
state
the connection state as a Symbol such as :connected or ConnectionState object to subscribe to
Type: ConnectionState
state
the connection state to subscribe to
Type: ARTRealtimeConnectionState
listener
is a function of the form function(stateChange) to be notified for matching state changes
listener
listener to be notified for matching state changes
Type: ConnectionStateListener
action
action to be executed for matching state changes
Type: ConnectionStateChange
&block
listener block that is yielded to for matching state changes
call
called with matching state changes

Example

Browser ConnectionState change example

onceOnce

There are two overloaded versions of this method:

once(String state, listener(ConnectionStateChange stateChange))once(ConnectionState *state) → yields ConnectionStateChangevoid once(ConnectionState state, ConnectionStateListener listener)once(event: ARTRealtimeConnectionState, call: (ARTConnectionStateChange?) → Void) → ARTEventListenervoid Once(ConnectionState event, Action<ConnectionStateChange> action)

Register the given listener blockfunctionaction for a single occurrence of the specified ConnectionState statestate(s)state change on the Connection. Once the listener has been called, it is removed as a registered listener and will not be called again. The listener is passed a ConnectionStateChange object that contains the current state, previous state, and an optional reason for the state change.

once(listener(ConnectionStateChange stateChange))once → yields ConnectionStateChangevoid once(ConnectionStateListener listener)once(call: (ARTConnectionStateChange?) → Void) → ARTEventListenervoid Once(Action<ConnectionStateChange> action)

Register the given listener blockaction for a single occurrence of any ConnectionState change on the Connection. Once the listener has been called, it is removed as a registered listener and will not be called again. The listener is passed a ConnectionStateChange object that contains the current state, previous state, and an optional reason for the state change.

Parameters

state
the connection state to subscribe to
Type: String
state
the connection state to subscribe to
Type: ConnectionState
event
the connection state to subscribe to
Type: ConnectionState
state
the connection state as a Symbol such as :connected or ConnectionState object to subscribe to
Type: ConnectionState
state
the connection state to subscribe to
Type: ARTRealtimeConnectionState
listener
is a function of the form function(stateChange) to be notified for a single occurrence of a matching state change
listener
listener to be notified for a single occurrence of a matching state change
Type: ConnectionStateListener
action
action to be executed for matching state changes
Type: ConnectionStateChange
&block
listener block that is yielded to for a single occurrence of a matching state change
call
called with matching state changes
offOff

There are two overloaded versions of this method:

off(String state, listener)off(ConnectionState *state, &block)void off(ConnectionState state, ConnectionStateListener listener)off(event: ARTRealtimeConnectionState, listener: ARTEventListener)void Off(ConnectionState event, Action<ConnectionStateChange> action)

Remove the given listener blockaction for the ConnectionState statestate(s)state.

off(listener)off(&block)void off(ConnectionStateListener listener)off(listener: ARTEventListener)void Off(Action<ConnectionStateChange> action)

Remove the given listener blockaction for all ConnectionState states.

Parameters

state
the connection state to unsubscribe from
Type: String
state
the connection state to unsubscribe from
Type: ConnectionState
event
the connection state to subscribe to
Type: ConnectionState
state
the connection state as a Symbol such as :connected or ConnectionState object to unsubscribe from
Type: ConnectionState
event
the connection state to unsubscribe from
Type: ARTRealtimeConnectionState
listener
is the listener function to be removed
listener
is the listener to be removed
Type: ConnectionStateListener
action
action to be executed for matching state changes
Type: ConnectionStateChange
&block
is the listener block to be removed
listener
previous return value from a on or once call
pingPing

ping(callback(ErrorInfo err))Deferrable ping → yields Float secondsvoid ping(CompletionListener listener)ping(callback: (ARTErrorInfo?) → Void)void Ping(Action<TimeSpan?, ErrorInfo> callback)

When connected, sends a heartbeat ping to the Ably server and executes the callbackcalls the listeneryields the elapsed time in seconds when a heartbeat ping request is echoed from the server. This can be useful for measuring true roundtrip latency to the connected Ably server.

Returns

A Deferrable object is returned from this method.

On successfully echoing a heartbeat from Ably, the registered success blocks for the Deferrable and any block provided to this method yields a Float representing the time in seconds for the heartbeat ping request to be echoed.

Failure to receive a heartbeat ping will trigger the errback callbacks of the Deferrable with an ErrorInfo object containing an error response as defined in the Ably REST API documentation.

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);
}

ConnectionStateARTRealtimeConnectionStateConnection::STATE Enumio.ably.lib.realtime.ConnectionState EnumIO.Ably.Realtime.ConnectionState Enum

ConnectionState is a String with a value matching any of the Realtime Connection states.

var allConnectionStates = [
  'initialized',
  'connecting',
  'connected',
  'disconnected',
  'suspended',
  'closing',
  'closed',
  'failed'
]

io.ably.lib.realtime.ConnectionState is an enum representing all the Realtime Connection states.

public enum ConnectionState {
  initialized,   // 0
  connecting,    // 1
  connected,     // 2
  disconnected,  // 3
  suspended,     // 4
  closing,       // 5
  closed,        // 6
  failed         // 7
}

IO.Ably.Realtime.ConnectionState is an enum representing all the Realtime Connection states.

public enum ConnectionState
{
    Initialized,    //0
    Connecting,     //1
    Connected,      //2
    Disconnected,   //3
    Suspended,      //4
    Closing,        //5
    Closed,         //6
    Failed          //7
};

Ably::Realtime::Connection::STATE is an enum-like value representing all the Realtime Connection states. STATE can be represented interchangeably as either symbols or constants.

Symbol states

:initialized # =>  0
:connecting # =>   1
:connected # =>    2
:disconnected # => 3
:suspended # =>    4
:closing # =>      5
:closed # =>       6
:failed # =>       7

Constant states

Connection::STATE.Initialized # =>  0
Connection::STATE.Connecting # =>   1
Connection::STATE.Connected # =>    2
Connection::STATE.Disconnected # => 3
Connection::STATE.Suspended # =>    4
Connection::STATE.Closing # =>      5
Connection::STATE.Closed # =>       6
Connection::STATE.Failed # =>       7

Example usage

# Example with symbols
client.connection.on(:connected) { ... }

# Example with constants
client.connection.on(Ably::Realtime::Connection::STATE.Connected) { ... }

# Interchangeable
Ably::Realtime::Connection::STATE.Connected == :connected # => true

ARTRealtimeConnectionState is an enum representing all the Realtime Connection states.

typedef NS_ENUM(NSUInteger, ARTRealtimeConnectionState) {
    ARTRealtimeInitialized,
    ARTRealtimeConnecting,
    ARTRealtimeConnected,
    ARTRealtimeDisconnected,
    ARTRealtimeSuspended,
    ARTRealtimeClosing,
    ARTRealtimeClosed,
    ARTRealtimeFailed
};
public enum ARTRealtimeConnectionState : UInt {
    case Initialized
    case Connecting
    case Connected
    case Disconnected
    case Suspended
    case Closing
    case Closed
    case Failed
}

io.ably.lib.realtime.ConnectionStateListener

A io.ably.lib.realtime.ConnectionStateListener is an interface allowing a client to be notified of connection state change. See Connection#on to register a listener for one or more events.

public interface ConnectionStateListener {
  // Called when the connection state changes
  public void onConnectionStateChanged(ConnectionStateListener.ConnectionStateChange state);
}

ConnectionStateChange ObjectARTConnectionStateChangeio.ably.lib.realtime.ConnectionStateListener.ConnectionStateChangeConnectionStateChangeIO.Ably.Realtime.ConnectionStateChange

A io.ably.lib.realtime.ConnectionStateListener.ConnectionStateChangeAbly::Models::ConnectionStateChangeARTConnectionStateChangeIO.Ably.Realtime.ConnectionStateChangeConnectionStateChange is a type encapsulating state change information emitted by the Connection object. See Connection#on to register a listener for one or more events.

PropertiesMembersAttributes

previousPrevious
the previous state
Type: State StringConnection::STATEConnectionState
currentCurrent
the new state
Type: State StringConnection::STATEConnectionState
reasonReason
an ErrorInfo containing any information relating to the transition
Type: ErrorInfo
retryInretry_inRetryIn
Duration upon which the library will retry a connection where applicable, as millisecondssecondsa Timespan
Type: IntegerTimespanLong Integer

LastConnectionDetails

A LastConnectionDetails object provides details on the last connection in a browser environment persisted when the window beforeunload fired. This object is provided to the callback specified in the recover attribute of ClientOptions. The callback in turn instructs the client library whether the connection should be recovered or not. See connection state recovery for more information.

Please note that as sessionStorage is used to persist the LastConnectionDetails between page reloads, it is only available for pages in the same origin and top-level browsing context.

Properties

recoveryKey
An opaque string obtained from the recoveryKey attribute of the Connection object before the page was unloaded. This property is used by the library to recover the connection
Type: String
disconnectedAt
the time at which the previous library was abruptly disconnected before the page was unloaded. This is represented as milliseconds since epoch
Type: Integer
location
a clone of location object of the previous page’s document object before the page was unloaded. A common use case for this attribute is to ensure that the previous page URL is the same as the current URL before allowing the connection to be recovered. For example, you may want the connection to be recovered only for page reloads, but not when a user navigates to a different page
Type: String
clientId
the clientId of the client’s Auth object before the page was unloaded. A common use case for this attribute is to ensure that the current logged in user’s clientId matches the previous connection’s clientId before allowing the connection to be recovered. Ably prohibits changing a clientId for an existing connection, so any mismatch in clientId during a recover will result in the connection moving to the failed state
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.