Warning: You are viewing an old version (0.8) of this documentation. We recommend you view the latest version 1.1.
Realtime Client Library API

Connection

The Ably Realtime library establishes and maintains a connection to the Ably service, using the most efficient transport available, typically WebSockets. The Ably realtime protocol operates and multiplexes all channel traffic over that connection.

Getting started

The Ably Realtime library will open and maintain a connection to the Ably realtime servers as soon as it is instanced. The Connection object provides a straightforward API to monitor and manage connection state.

The following example relies on the default auto-connect behaviour of the library, and then subscribes to the connection’s connected event.

var ably = new Ably.Realtime('xVLyHw.FOCD5w:uKECEtCz-xo_dCBe');
ably.connection.on('connected', function() {
  alert('Connected, that was easy');
})
var Ably = require('ably');
var ably = new Ably.Realtime('xVLyHw.FOCD5w:uKECEtCz-xo_dCBe');
ably.connection.on('connected', function() {
  console.log('Connected, that was easy');
})
ably = Ably::Realtime.new('xVLyHw.FOCD5w:uKECEtCz-xo_dCBe')
ably.connection.on(:connected) do
  puts "Connected, that was easy"
end
AblyRealtime ably = new AblyRealtime("xVLyHw.FOCD5w:uKECEtCz-xo_dCBe");
ably.connection.on('connected', new ConnectionStateListener() {
  @Override
  public void onConnectionStateChanged(ConnectionStateChange change) {
    System.out.println("Connected, that was easy");
  }
});
AblyRealtime ably = new AblyRealtime("xVLyHw.FOCD5w:uKECEtCz-xo_dCBe");
ably.Connection.On(ConnectionState.Connected, args => {
  Console.WriteLine("Connected, that was easy");
});
ARTRealtime *ably = [[ARTRealtime alloc] initWithKey:@"xVLyHw.FOCD5w:uKECEtCz-xo_dCBe"];
[ably.connection on:ARTRealtimeConnectionEventConnected call:^(ARTConnectionStateChange *change) {
    NSLog(@"Connected, that was easy");
}];
let realtime = ARTRealtime(key: "xVLyHw.FOCD5w:uKECEtCz-xo_dCBe")
realtime.connection.on(.connected) { change in
    print("Connected, that was easy")
}

Connection state explained

Although connection state is temporary, the Ably protocol provides continuity of message delivery between the client and the service, provided that a dropped connection is reestablished by the client within a limited interval (typically around 2 minutes). Beyond that, the connection becomes stale and the system will not attempt to recover the connection state. The lifecycle of a connection, and the strategy for reconnecting on failure, reflect the transient nature of the connection state.

The client library is responsible for managing the connection; this includes selecting a transport (in those environments supporting multiple transports), selecting a host to connect to (automatically falling back to an alternate data centre host if the closest data centre is unreachable), and managing continuity of operation when the connection drops.

When the library is instanced, if connectivity to the service is available, the library will establish a connection immediately, and if the connection drops at any time it will attempt to re-establish it by making repeated connection attempts every 15 seconds for up to two minutes.

If, after that time, there has been no connection, the library falls back to a lower level of activity, still periodically attempting reconnection at 30 second intervals. This reflects the assumption that there will no longer be recoverable connection state and the client may be offline for a period of time. As soon as a reconnection attempt has been successful, the system reverts to the more active connection behaviour. Further, you can explicitly trigger a reconnection attempt at any time if you wish to implement a different reconnection strategy.

The connection object provides methods to observe the lifecycle of the connection and to trigger state transitions.

Available connection states

A series of connection states is defined as follows:

initializedInitialized
A Connection object having this state has been initialized but no connection has yet been attempted.
connectingConnecting
A connection attempt has been initiated. The connecting state is entered as soon as the library has completed initialization, and is reentered each time connection is re-attempted following disconnection.
connectedConnected
A connection exists and is active.
disconnectedDisconnected
A temporary failure condition. No current connection exists because there is no network connectivity or no host is available.

The disconnected state is entered if an established connection is dropped, or if a connection attempt was unsuccessful. In the disconnected state the library will periodically attempt to open a new connection (approximately every 15 seconds), anticipating that the connection will be re-established soon and thus connection and channel continuity will be possible.

In this state, developers can continue to publish messages as they are automatically placed in a local queue, and sent as soon as a connection is established.
Messages published by other clients to the Ably service, whilst this client is disconnected, are queued and delivered to this client upon reconnection, so long as the connection is resumed within 2 minutes.

If connection state recovery is not possible following a new connection being established, all channels are detached, thus ensuring the developer is made aware that continuity on the channel was not possible. The developer is then responsible for re-attaching channels and recovering state, if required, using the history API.
suspendedSuspended
A long term failure condition. No current connection exists because there is no network connectivity or no host is available.

The suspended state is entered after a failed connection attempt if there has then been no connection for a period of two minutes. In the suspended state, the library will periodically attempt to open a new connection every 30 seconds. Developers are unable to publish messages in this state. A new connection attempt can also be triggered by an explicit call to connect()connectConnect() on the Connection object.
closingClosing
An explicit request by the developer to close the connection has been sent to the Ably service. If a reply is not received from Ably within a short period of time, the connection will be forcibly terminated and the connection state will become closedClosed.
closedClosed
The connection has been explicitly closed by the client.

In the closed state, no reconnection attempts are made automatically by the library, and clients may not publish messages. No connection state is preserved by the service or by the library. A new connection attempt can be triggered by an explicit call to connect()connectConnect() on the Connection object, which will result in a new connection.
failedFailed
An indefinite failure condition. This state is entered if a connection error has been received from the Ably service (such as an attempt to connect with invalid credentials). A failed state may also be triggered by the client library directly as a result of some local permanent error.

In the failed state, no reconnection attempts are made automatically by the library, and clients may not publish messages. A new connection attempt can be triggered by an explicit call to connect()connectConnect() on the Connection object.

Typical connection state sequences

The library is initialized and initiates a successful connection.

initialized → connecting → connectedInitialized → Connecting → Connected

An existing connection is dropped and reestablished on the first attempt.

connected → disconnected → connecting → connectedConnected → Disconnected → Connecting → Connected

An existing connection is dropped, and reestablished after several attempts but within a two minute interval.

connected → disconnected → connecting → disconnected → … → connecting → connectedConnected → Disconnected → Connecting → Disconnected → … → Connecting → Connected

There is no connection established after initializing the library.

initialized → connecting → disconnected → connecting → … → suspendedInitialized → Connecting → Disconnected → Connecting → … → Suspended

After a period of being offline a connection is reestablished.

suspended → connecting → suspended → … → connecting → connectedSuspended → Connecting → Suspended → … → Connecting → Connected

Listening for state changes

The Connection object is an EventEmitter and emits an event whose name is the new state whenever there is a connection state change. An event listener function is passed a ConnectionStateChange object as the first argument for state change events.An event listener function is passed a ConnectionStateChange object as the first argument for state change events.The event block is passed the new state and an optional ErrorInfo object

realtime.connection.on('connected', function(stateChange) {
  console.log('Ably is connected');
});
realtime.connection.on('connected', function(stateChange) {
  console.log('Ably is connected');
});

Alternatively a listener may be registered so that it receives all state change events.

realtime.connection.on(function(stateChange) {
  console.log('New connection state is ' + stateChange.current);
});
realtime.connection.on(function(stateChange) {
  console.log('New connection state is ' + stateChange.current);
});

Previously registered listeners can be removed individually or all together.

/* remove a listener registered for a single event */
realtime.connection.off('connected', myListener);

/* remove a listener registered for all events */
realtime.connection.off(myListener);

/* remove all event listeners */
realtime.connection.off();
/* remove a listener registered for a single event */
realtime.connection.off('connected', myListener);

/* remove a listener registered for all events */
realtime.connection.off(myListener);

/* remove all event listeners */
realtime.connection.off();
realtime.connection.on(ConnectionState.connected, new ConnectionStateListener() {
  @Override
  public void onConnectionStateChanged(ConnectionStateChange change) {
    System.out.println("New state is connected");
  }
});

Alternatively a listener may be registered so that it receives all state change events.

realtime.connection.on(new ConnectionStateListener() {
  @Override
  public void onConnectionStateChanged(ConnectionStateChange change) {
    System.out.println("New state is " + change.current.name());
  }
});

Previously registered listeners can be removed individually or all together.

/* remove a single listener */
realtime.connection.off(myListener);

/* remove all event listeners */
realtime.connection.off();
realtime.Connection.On(ConnectionState.Connected, args => {
  Console.WriteLine("Connected, that was easy");
});

Alternatively a handler may be registered so that it receives all state change events.

realtime.Connection.On(args => {
  Console.WriteLine("New state is " + args.Current);
});

Previously registered handlers can be removed individually or all together.

/* remove a single handler */
realtime.Connection.Off(action);

/* remove all event handlers */
realtime.Connection.Off();
realtime.connection.on(:connected) do
  puts 'Ably is connected'
end

Alternatively a listener may be registered so that it receives all state change events.

realtime.connection.on do |state_change|
  puts "New connection state is #{state_change.current}"
end

Previously registered listeners can be removed individually or all together.

# remove a listener registered for a single even
realtime.connection.off :connected, &block

# remove a listener registered for all events
realtime.connection.off &block

# remove all event listeners
realtime.connection.off
ARTEventListener *listener = [realtime.connection on:ARTRealtimeConnectionEventConnected call:^(ARTConnectionStateChange *change) {
    NSLog(@"Ably is connected");
}];

Alternatively a listener may be registered so that it receives all state change events.

ARTEventListener *listener = [realtime.connection on:^(ARTConnectionStateChange *change) {
    NSLog(@"New connection state is %lu", (unsigned long)change.current);
}];

Previously registered listeners can be removed individually or all together.

// remove a listener registered for a single event
[realtime.connection off:ARTRealtimeConnectionEventConnected listener:listener];

// remove a listener registered for all events
[realtime.connection off:listener];

// remove all event listeners
[realtime.connection off];
let listener = realtime.connection.on(.connected) { change in
    print("Ably is connected")
}

Alternatively a listener may be registered so that it receives all state change events.

let listener = realtime.connection.on { change in
    print("New connection state is \(change!.current)")
}

Previously registered listeners can be removed individually or all together.

// remove a listener registered for a single event
realtime.connection.off(.connected, listener: listener)

// remove a listener registered for all events
realtime.connection.off(listener)

// remove all event listeners
realtime.connection.off()

Handling failures

We recommend that you always handle both connection and channel failures explicitly. For example, a connection can move to the FAILED state if the token cannot be renewed successfully, or a channel can move to the DETACHED state if there is a loss of continuity on the channel. If you subscribe to these failure states that are not automatically recovered, you can perform your own recovery based on your specific application requirements. The failure states you need to consider are:

State change side effects on channels

Once a channel becomes attached, it will remain attached until any of the following occurs:

  • An explicit request to detach the channel is made;
  • The channel moves into the failedFailed state following an unrecoverable error sent from Ably. If for example permissions were revoked for that client on that channel, the channel would move to the failedFailed state;
  • The connection enters the suspendedSuspended, failedFailed or closedClosed state;
  • The connection is not resumed fully as part of the connection state recovery process

Ably provides automatic message continuity for channels, even when connections are disconnected and later resumed. See connection state recovery for more details on how connections and channel state recovery allows you, as a developer, to publish and receive messages without having to worry about changing network conditions. However, there are times when connection recovery is not possible such as being disconnected from Ably for more than two minutes. When this occurs, the channels that are attached can no longer provide guaranteed message continuity. We wanted developers to be aware of this discontinuity, and as such, our client libraries will automatically detach all attached channels that have lost continuity. It is then up to the developer to decide what action to take such as using the history API to retrieve old messages, or simply to reattach the channel and continue if message loss is not important.

For customers who want to ensure that all channels are attached when a connection is available, regardless of whether messages may have been missed, we recommend the following approach:

  • Add a listener on the connection object for all connectedConnected events
  • Reattach all channels you have created. If a channel is already attached, and you call the channel#attachchannel#Attach method, the channel will simply remain attached. It is therefore safe to simply attach all channels every time the connection becomes connected

The following Javascript example demonstrates a trivial way to ensure all channels are attached when the client becomes connected or the channel becomes detached:

function reattach(channel) {
  channel.attach();
  /* Example when using presence on the channel */
  channel.presence.enter();
}

/* Connection state changes can trigger channels to become detached
   Automatically re-attach channels, nothing will happen if already attached */
client.connection.on('connected', function() {
  for (let channelName in client.channels.all) {
    let channel = client.channels.get(channelName);
    reattach(channel);
  }
});

/* If a channel becomes detached due to channel failure (some edge cases exist)
   You should explicitly re-attach the channel if you are connected */
channel.on('detached', function() {
  if (client.connection.state === 'connected') {
    reattach(channel);
  }
});

Connection state recovery

The Ably system preserves connection state to allow connections to continue transparently across brief disconnections. The connection state that is tracked includes the messages sent to the client on the connection, members present on a channel and the set of channels that the client is attached to.

There are two modes of connection state recovery:

  • resume: this is transparent recovery of a live client instance across disconnections. Upon disconnection, the library will automatically re-attempt connection and, once the connection is re-established, any missed messages will be sent to the client. The developer does not need to do anything to trigger this behaviour; all client channel event listeners remain attached and are called when the backlog of messages is received.
  • recover: this addresses the case in which a new client library instance wishes to connect and recover the state of an earlier connection. This occurs typically in a browser environment when the page has been refreshed and therefore the client instance is disposed and no client state is retained. In this case any message listeners associated with channels will no longer exist so it is not possible for the library simply to send the message backlog on reconnection; instead the client must re-subscribe to each channel it is interested in within 15 seconds, and its message listener(s) will be called with any message backlog for that channel. If the previously attached channels are not re-attached within 15 seconds of a connection being recovered, the channels will automatically be detached by Ably. A client requests recovery of connection state by including a recovery string in the client options when instancing the Realtime library. See connection state recover options for more info.

In either case, when a connection is resumed or recovered, the message backlog held on the server will be pushed to the client. However, any new messages published will be sent as they become available or messages could be indefinitely deferred on very heavily loaded connections. Therefore the system does not guarantee that messages received after reconnection are delivered in the same order that would have occurred if the connection had not been dropped. In the recover case, in particular, the order of the message delivery depends on the timing of the re-attachment of each channel.

Connection state recover options

In recover mode it is necessary to request recovery mode in the client options when instancing the library. Recovery requires that the library knows the previous connection’s recoveryKeyrecovery_keyRecoveryKey value (which includes both the private unique Connection#keyConnection#Key and the last message serial received on that connection). As the recovery key is never shared with any other clients, it allows Ably to safely resend message backlogs to the original client.

In the browser environment, if a callback is provided in the recover option, when window beforeunload event fires, the connection details, including the recoveryKey, are stored in the browser’s sessionStorage. The provided recover callback is then invoked whenever the connection state can be recovered and just before a connection is established, passing in the LastConnectionDetails. The callback is then responsible for confirming whether the connection state should be recovered or not. For example, it is common to recover connection state when the page is reloaded but not for different pages the user has navigated to. The callback allows the developer to decide if the connection should be recovered or not at the time the new connection is established by inspecting the LastConnectionDetails and evaluating that against any other application state. Below is a straightforward example:

var ably = new Ably.Realtime({
  authUrl: '/obtainToken',
  recover: function(lastConnectionDetails, cb) {
    if (lastConnectionDetails.location.href === document.location.href) {
      cb(true); /* recover connection as user has reloaded page */
    } else {
      cb(false); /* do not recover connection as URL has changed */
    }
  }
});
var ably = new Ably.Realtime({
  authUrl: '/obtainToken',
  recover: function(lastConnectionDetails, cb) {
    if (lastConnectionDetails.location.href === document.location.href) {
      cb(true); /* recover connection as user has reloaded page */
    } else {
      cb(false); /* do not recover connection as URL has changed */
    }
  }
});

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.

Alternatively, if it is necessary to be explicit about the connection recoveryKey , the connection can be recovered by providing the last value of the connection’s recoveryKey value in the client options recover attribute when instancing the library.

Connection recovery constraints

Connection recovery requires that the new client library instance uses credentials that are compatible with those used for the inherited connection; this requires that the same authentication mode is used, with the same key. If token auth was used, the same token is not required, but the token used must have the same capability and clientIdclient_idClientId. This ensures that the client recovering the connection cannot receive a backlog of messages that its new credentials are not entitled to access. Incompatible credentials will result in an unrecoverable connection error.

Connection API reference

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

API reference
Documentation

Ready to get started?

Our free plan includes 3m messages per month, 100 peak connections, 100 peak channels, and loads of features.