Connection

Open in

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:

statusConnectionStatus
The current connection status.
errorErrorInfo or Undefined
The error that caused the connection to enter its current status, if any.

Subscribe to connection status changes

connection.onStatusChange(listener: ConnectionStatusListener): StatusSubscription

Registers 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:

listenerrequiredConnectionStatusListener
A callback invoked on status changes.

Returns

StatusSubscription

Returns an object with the following methods:

Deregister the listener

off(): void

Call 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();