Connection
The Connection interface represents the connection to Ably and provides methods to inspect the connection state, listen for state changes, and explicitly open or close the connection. Access it via the connection property of a Realtime client instance.
1
const connection = realtime.connection;Properties
The Connection interface has the following properties:
idStringstateConnectionStateerrorReasonErrorInfo or UndefinedkeyStringrecoveryKey is used in the clientOptions.recover option 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 realtime client.Connect to Ably
connection.connect(): voidExplicitly calling connect() is unnecessary unless clientOptions.autoConnect is false. Unless already connected or connecting, this method causes the connection to open, entering the connecting state.
1
2
realtime.connection.connect();
await realtime.connection.once('connected');Close the connection
connection.close(): voidCauses the connection to close, entering the closing state. Once closed, the SDK will not attempt to re-establish the connection without an explicit call to connect().
1
realtime.connection.close();Register a state change listener
connection.on(event: ConnectionEvent, listener: connectionEventCallback): voidRegister the given listener for the specified ConnectionEvent on the Connection. The listener is passed a ConnectionStateChange object that contains the current state, previous state, the event, and an optional reason for the event or state change.
connection.on(events: ConnectionEvent[], listener: connectionEventCallback): voidRegisters the listener for each event in the array.
connection.on(listener: connectionEventCallback): voidRegister the given listener for all ConnectionEvents on the Connection. The listener is passed a ConnectionStateChange object that contains the current state, previous state, the event, and an optional reason for the event or state change. For the update event, the current and previous states will be the same.
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.
1
2
3
4
5
6
7
realtime.connection.on('connected', (stateChange) => {
console.log('Connected to Ably');
});
realtime.connection.on(['disconnected', 'suspended'], (stateChange) => {
console.log('Connection lost:', stateChange.reason);
});Parameters
The on() method takes the following parameters:
eventoptionalConnectionEventeventsoptionalConnectionEvent[]listenerrequiredconnectionEventCallbackevent nor events is supplied, it fires for every event.Register a one-time state change listener
connection.once(event: ConnectionEvent, listener: connectionEventCallback): voidRegister the given listener for a single occurrence of the specified ConnectionEvent on the Connection. Once the listener has been called, it is removed as a registered listener and will not be called again.
connection.once(listener: connectionEventCallback): voidRegister the given listener for a single occurrence of any ConnectionEvent on the Connection.
connection.once(event: ConnectionEvent): Promise<ConnectionStateChange>Returns a promise that is fulfilled with the next ConnectionStateChange for the specified event. This is the preferred way to await a specific connection state from async code.
connection.once(): Promise<ConnectionStateChange>Returns a promise that is fulfilled with the next ConnectionStateChange, regardless of the event type.
1
2
await realtime.connection.once('connected');
console.log('Connected');Parameters
The once() method takes the following parameters:
eventoptionalConnectionEventlisteneroptionalconnectionEventCallbackReturns
The callback-based overloads return void.
The promise-based overloads return Promise<ConnectionStateChange>. The promise is fulfilled with a ConnectionStateChange object the next time a matching event occurs, or rejected with an ErrorInfo object if the connection enters a state from which the event cannot occur.
Remove a state change listener
connection.off(event: ConnectionEvent, listener: connectionEventCallback): voidRemove the given listener for the specified ConnectionEvent.
connection.off(listener: connectionEventCallback): voidRemove the given listener for all ConnectionEvents.
connection.off(): voidRemoves all listeners, including those registered with and without specific events.
1
2
3
4
5
6
7
8
const listener = (stateChange) => console.log(stateChange.current);
realtime.connection.on('connected', listener);
// Remove the specific listener for 'connected'
realtime.connection.off('connected', listener);
// Remove all listeners
realtime.connection.off();Parameters
The off() method takes the following parameters:
eventoptionalConnectionEventlisteneroptionalconnectionEventCallbackPing the Ably service
connection.ping(): Promise<number>When connected, sends a heartbeat ping to the Ably server and returns the round-trip time in milliseconds when a heartbeat ping response is received from the server. Useful for measuring the true round-trip latency to the connected Ably server.
1
2
const latency = await realtime.connection.ping();
console.log(`Latency: ${latency}ms`);Returns
Promise<number>
Returns a promise. The promise is fulfilled with a number representing the time in milliseconds for the heartbeat ping request to be echoed, or rejected with an ErrorInfo object that details the reason why it was rejected.
Get registered listeners
connection.listeners(eventName?: ConnectionEvent): null | connectionEventCallback[]Returns the listeners registered for the specified ConnectionEvent. If eventName is omitted, returns all registered listeners.
Parameters
The listeners() method takes the following parameters:
eventNameoptionalConnectionEventReturns
null | connectionEventCallback[]
Returns an array of registered listener functions, or null if no listeners are registered for the specified event.
Wait for a connection state
connection.whenState(targetState: ConnectionState): Promise<null | ConnectionStateChange>If the connection is already in the given state, returns a promise which immediately resolves to null. Otherwise calls once() to return a promise which resolves the next time the connection transitions to the given state.
1
await realtime.connection.whenState('connected');Parameters
The whenState() method takes the following parameters:
targetStaterequiredConnectionStateReturns
Promise<null | ConnectionStateChange>
Returns a promise. If the connection is already in the given state, the promise immediately resolves to null. Otherwise it resolves with a ConnectionStateChange the next time the connection transitions to that state.
Create a connection recovery key
connection.createRecoveryKey(): null | stringGenerates a string that can be used by another client to recover the current connection's state using clientOptions.recover, as described in the connection state recovery options.
1
const recoveryKey = realtime.connection.createRecoveryKey();Returns
null | string
Returns a recovery key string, or null if a recovery key cannot be generated (for example, if the connection has never been connected).