The Connection interface represents the connection to Ably and provides methods to monitor connection status changes. Access the connection via chatClient.connection.
JavaScript
1
const connection = chatClient.connection;Properties
The Connection interface has the following properties:
statusConnectionStatusThe current connection status.
errorErrorInfo or UndefinedThe error that caused the connection to enter its current status, if any.
Subscribe to connection status changes
connection.onStatusChange(listener: ConnectionStatusListener): StatusSubscriptionRegisters a listener to be notified of connection status changes.
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
const { off } = chatClient.connection.onStatusChange((change) => {
console.log('Status changed from', change.previous, 'to', change.current);
if (change.error) {
console.error('Error:', change.error);
}
if (change.retryIn) {
console.log('Retrying in', change.retryIn, 'ms');
}
});
// To unsubscribe
off();Parameters
The onStatusChange() method takes the following parameters:
listenerrequiredConnectionStatusListenerA callback invoked on status changes.
Returns
StatusSubscription
Returns an object with the following methods:
Deregister the listener
off(): voidCall off() to deregister the connection status listener.
Example
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import { ConnectionStatus } from '@ably/chat';
// Monitor connection status
const { off } = chatClient.connection.onStatusChange((change) => {
switch (change.current) {
case ConnectionStatus.Connected:
console.log('Connected to Ably');
break;
case ConnectionStatus.Disconnected:
console.log('Disconnected, will retry...');
break;
case ConnectionStatus.Suspended:
console.log('Connection suspended, retrying in', change.retryIn, 'ms');
break;
case ConnectionStatus.Failed:
console.error('Connection failed:', change.error);
break;
}
});
// Check current status
console.log('Current status:', chatClient.connection.status);
// Clean up when done
off();