RealtimeChannel

A RealtimeChannel represents a single channel, obtained via the channels.get() method. Use it to publish and subscribe to messages, manage channel state, and access channel features such as presence, push notifications, and annotations.

JavaScript

1

const channel = realtime.channels.get('all-gas-ion');

Properties

The RealtimeChannel interface has the following properties:

nameString
The name of this channel.
stateChannelState
The current channel state.
errorReasonErrorInfo or Undefined
When a channel failure occurs, this property contains the error.
Access the RealtimePresence object for this channel.
Access the PushChannel object for this channel.
Access the RealtimeAnnotations object for this channel, used to publish, delete, retrieve, and subscribe to annotations on messages.
paramsRecord<String, String>
The current channel parameters in effect for this channel.
modesResolvedChannelMode[]
The current channel modes in effect for this channel.

Subscribe to messages

channel.subscribe(listener: messageCallback): Promise<ChannelStateChange | null>

Subscribe to all messages on this channel. The listener is called for every message received.

channel.subscribe(event: string, listener?: messageCallback): Promise<ChannelStateChange | null>

Subscribe only to messages with a specific event name (client-side filter).

channel.subscribe(events: string[], listener?: messageCallback): Promise<ChannelStateChange | null>

Subscribe to messages matching any event name in the array (client-side filter).

channel.subscribe(filter: MessageFilter, listener?: messageCallback): Promise<ChannelStateChange | null>

Register a listener for messages on this channel that match the supplied filter. Filtering happens server-side as part of filtered subscriptions.

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

// All messages
await channel.subscribe((message) => {
  console.log(message.name, message.data);
});

// Specific event
await channel.subscribe('greeting', (message) => {
  console.log('Hi:', message.data);
});

// Server-side filter (filtered subscription)
await channel.subscribe({ name: 'click', clientId: 'user-123' }, (message) => {
  console.log('Filtered:', message.data);
});

If the channel is initialized, calling subscribe() implicitly attaches the channel.

Calling subscribe() with an event name is a client-side filter. All messages are still sent over the wire, regardless of name. To filter messages server-side, use filtered subscriptions with a filter argument.

When subscribing, keep the following behaviours in mind:

  • If subscribe() is called more than once with the same listener, duplicates are registered. If you subscribe twice with the same listener and a message is later received, that listener is invoked twice.
  • A registered listener remains active on the channel regardless of the current channel state. If you subscribe when a channel is attached and it later becomes detached or failed, the listener is still invoked when the channel reattaches and a message is received. Listeners are only removed by calling unsubscribe() or when the channel is released using channels.release().
  • If an exception is thrown in a listener and bubbles up to the event emitter, it is caught and logged at error level, so as not to affect other listeners for the same event.

Parameters

The subscribe() method takes the following parameters:

eventoptionalString
The event name to subscribe to.
eventsoptionalString[]
An array of event names to subscribe to.
filteroptionalMessageFilter
A filter object used to filter messages server-side.
listeneroptionalFunction
A function called with each matching Message. Required when subscribing to all messages; with an event, events, or filter argument it may be omitted to attach the channel without registering a listener.

Returns

Promise<ChannelStateChange | null>

Returns a promise. On successful channel attachment, the promise is fulfilled with a ChannelStateChange. If the channel was already attached, the promise resolves with null. On failure, the promise is rejected with an ErrorInfo object.

Publish a message

channel.publish(name: string, data: any, options?: PublishOptions): Promise<PublishResult>

Publish a single message on the channel based on a given event name and payload.

channel.publish(message: Message, options?: PublishOptions): Promise<PublishResult>

Publish a single message object on the channel.

channel.publish(messages: Message[], options?: PublishOptions): Promise<PublishResult>

Publish multiple messages atomically on the channel. This means that:

  • Either all messages will be successfully published or none of them will.
  • The max message size limit applies to the total size of all messages in the array.
  • The publish counts as a single message for the purpose of per-channel rate limit.
  • If you are using client-specified message IDs, they must conform to certain restrictions.

When publish() is called, the SDK will not implicitly attach to the channel so long as transient publishing is available. Otherwise, it will implicitly attach.

JavaScript

1

2

3

4

5

6

7

8

9

10

await channel.publish('greeting', 'Hello, World!');

// Or with a Message object
await channel.publish({ name: 'greeting', data: 'Hello' });

// Or atomic batch
await channel.publish([
  { name: 'event1', data: 'one' },
  { name: 'event2', data: 'two' }
]);

Parameters

The publish() method takes the following parameters:

namerequiredString
The event name.
datarequiredAny
The data payload for the message. Supported payload types are strings, JSON-serializable objects and arrays, buffers containing arbitrary binary data, and null. If sending binary data, that binary should be the entire payload; an object with a binary field within it may not be correctly encoded.
messagerequiredMessage
A single Message object to publish.
messagesrequiredMessage[]
An array of Message objects to publish atomically.
optionsoptionalObject
An open map of server-defined publish options (string, number, or boolean values). The SDK passes these through as publish parameters; the set of valid options is defined by the Ably service, not the SDK.

Returns

Promise<PublishResult>

Returns a promise. The promise is fulfilled with a PublishResult when the message(s) have been delivered to Ably, or rejected with an ErrorInfo object.

serialsArray of String or Null
An array of message serials corresponding 1:1 to the messages that were published. A serial may be null if the message was discarded due to a message conflation.

Update a message

channel.updateMessage(message: Message, operation?: MessageOperation, options?: PublishOptions): Promise<UpdateDeleteResult>

Publish an update to an existing message using shallow mixin semantics. Non-null name, data, and extras fields in the provided message replace the corresponding fields in the existing message; null fields are left unchanged. Requires the message-update-own or message-update-any capability.

Parameters

The updateMessage() method takes the following parameters:

messagerequiredMessage
The message to update. Must include the serial of the message being updated.
operationoptionalMessageOperation
Metadata about the update operation.
optionsoptionalObject
Server-defined options affecting the publish of the update.

Returns

Promise<UpdateDeleteResult>

Returns a promise. The promise is fulfilled with an UpdateDeleteResult containing the updated version metadata, or rejected with an ErrorInfo object.

versionSerialString or Null
The serial of the new version of the message produced by the update, delete, or append operation. null if the message was superseded by a subsequent update before it could be published.

Append to a message

channel.appendMessage(message: Message, operation?: MessageOperation, options?: PublishOptions): Promise<UpdateDeleteResult>

Append data to an existing message on the channel. The supplied data is appended to the previous message's data, while name and extras replace the previous values if provided. Subscribers receive a message.append action. Requires the message-update-own or message-update-any capability.

Parameters

The appendMessage() method takes the following parameters:

messagerequiredMessage
The message to append data to. Must include the serial of the target message.
operationoptionalMessageOperation
Metadata about the append operation.
optionsoptionalObject
Server-defined options affecting the publish of the append.

Returns

Promise<UpdateDeleteResult>

Returns a promise. The promise is fulfilled with an UpdateDeleteResult, or rejected with an ErrorInfo object.

Delete a message

channel.deleteMessage(message: Message, operation?: MessageOperation, options?: PublishOptions): Promise<UpdateDeleteResult>

Mark a message as deleted by publishing an update with an action of MESSAGE_DELETE. This does not remove the message from the server, and the full message history remains accessible. Uses shallow mixin semantics: non-null name, data, and extras fields in the provided message replace the corresponding fields in the existing message; null fields are left unchanged. Subscribers receive a message.delete action. Requires the message-delete-own or message-delete-any capability.

Parameters

The deleteMessage() method takes the following parameters:

messagerequiredMessage
The message to delete. Must include the serial of the message being deleted.
operationoptionalMessageOperation
Metadata about the delete operation.
optionsoptionalObject
Server-defined options affecting the publish of the delete.

Returns

Promise<UpdateDeleteResult>

Returns a promise. The promise is fulfilled with an UpdateDeleteResult, or rejected with an ErrorInfo object.

Get a single message by serial

channel.getMessage(serialOrMessage: string | Message): Promise<Message>

Retrieve the latest version of a message by its serial. Requires the history capability.

Parameters

The getMessage() method takes the following parameters:

serialOrMessagerequiredString or Message
Either the serial identifier string of the message to retrieve, or a Message object containing a populated serial field.

Returns

Promise<Message>

Returns a promise. The promise is fulfilled with the Message, or rejected with an ErrorInfo object.

Unsubscribe from messages

channel.unsubscribe(event: string, listener: messageCallback): void

Remove the given listener for the specified event.

channel.unsubscribe(events: string[], listener: messageCallback): void

Remove the given listener from all events in the array.

channel.unsubscribe(event: string): void

Remove all listeners registered for the specified event.

channel.unsubscribe(events: string[]): void

Remove all listeners registered for any event in the array.

channel.unsubscribe(filter: MessageFilter, listener?: messageCallback): void

Remove the listener registered for the specified filter, or all listeners for the filter if listener is omitted.

channel.unsubscribe(listener: messageCallback): void

Remove the given listener from all events.

channel.unsubscribe(): void

Remove all message listeners on this channel.

JavaScript

1

channel.unsubscribe();

Parameters

The unsubscribe() method takes the following parameters:

eventoptionalString
A single event name to stop listening to.
eventsoptionalString[]
An array of event names to stop listening to.
filteroptionalMessageFilter
The message filter whose listener should be removed.
listeneroptionalFunction
The listener to remove. If omitted, all listeners matching the supplied event(s) or filter are removed; if no arguments are given, all message listeners on the channel are removed.

Attach to the channel

channel.attach(): Promise<ChannelStateChange | null>

Attach to the channel. This first attempts to connect to Ably if not already connected, then sends an attach message for this channel. If the channel is already attached, this is a no-op and the promise resolves with null.

As a convenience, attach() is called implicitly if subscribe() is called on the channel, or if presence.enter() or presence.subscribe() is called on the channel's presence.

JavaScript

1

await channel.attach();

Returns

Promise<ChannelStateChange | null>

Returns a promise. The promise is fulfilled with a ChannelStateChange describing the transition to attached, or null if the channel was already attached. Rejected with an ErrorInfo object if the attach fails.

Detach from the channel

channel.detach(): Promise<void>

Detach from the channel. Any resulting channel state change is emitted to listeners registered using on() or once(). Once all clients globally have detached from the channel, the channel is released in the Ably service within two minutes.

JavaScript

1

await channel.detach();

Returns

Promise<void>

Returns a promise. The promise is fulfilled when the channel has been detached, or rejected with an ErrorInfo object.

Set channel options

channel.setOptions(options: ChannelOptions): Promise<void>

Configure the channel with new ChannelOptions. If the channel is already attached and the new options require a re-attach (for example, new channel modes or new params), the channel will be re-attached with the new options.

JavaScript

1

await channel.setOptions({ cipher: { key } });

Parameters

The setOptions() method takes the following parameters:

optionsrequiredChannelOptions
The new channel options.

Returns

Promise<void>

Returns a promise. The promise is fulfilled once the options have been applied (and the channel re-attached if required), or rejected with an ErrorInfo object.

Register a channel state listener

channel.on(event: ChannelEvent, listener: channelEventCallback): void

Register a listener for a single channel event.

channel.on(events: ChannelEvent[], listener: channelEventCallback): void

Register a listener for any of an array of channel events.

channel.on(listener: channelEventCallback): void

Register a listener for all channel events.

In every form the listener receives a ChannelStateChange object describing the transition.

If an exception is thrown in the listener and bubbles up to the event emitter, it is caught and logged at error level, so as not to affect other listeners.

JavaScript

1

2

3

channel.on('attached', (stateChange) => {
  console.log('Now attached');
});

Parameters

The on() method takes the following parameters:

eventoptionalChannelEvent
A single channel event to listen for.
eventsoptionalChannelEvent[]
An array of channel events to listen for.
listenerrequiredchannelEventCallback
A function invoked for each matching event. If neither event nor events is supplied, it fires for every event.

Register a one-time channel state listener

channel.once(event: ChannelEvent, listener: channelEventCallback): void

Register a one-time listener for a single channel event. It is invoked the next time that event occurs, then removed.

channel.once(listener: channelEventCallback): void

Register a one-time listener for the next channel event of any type.

channel.once(event: ChannelEvent): Promise<ChannelStateChange>

Return a promise that resolves the next time the specified event occurs.

channel.once(): Promise<ChannelStateChange>

Return a promise that resolves the next time any event occurs.

The callback-based forms return void; the promise-based forms return a promise that resolves with the next matching ChannelStateChange.

If an exception is thrown in the listener and bubbles up to the event emitter, it is caught and logged at error level, so as not to affect other listeners.

JavaScript

1

await channel.once('attached');

Parameters

The once() method takes the following parameters:

eventoptionalChannelEvent
The channel event to listen for. If omitted, the listener fires for any event.
listeneroptionalchannelEventCallback
A function invoked once with the next matching event. Omit to return a promise instead.

Returns

The callback-based overloads return void.

The promise-based overloads return Promise<ChannelStateChange>, fulfilled with a ChannelStateChange the next time a matching event occurs.

Remove a channel state listener

channel.off(event: ChannelEvent, listener: channelEventCallback): void

Remove the given listener for a specific channel event.

channel.off(listener: channelEventCallback): void

Remove the given listener from all channel events.

channel.off(): void

Remove all channel state listeners.

JavaScript

1

channel.off();

Parameters

The off() method takes the following parameters:

eventoptionalChannelEvent
The channel event to stop listening to. If omitted, the listener is removed from all events.
listeneroptionalchannelEventCallback
The listener to remove. If omitted, all listeners (for the given event, or for the whole channel) are removed.

Get registered listeners

channel.listeners(eventName?: ChannelEvent): null | channelEventCallback[]

Returns the channel state listeners registered for the specified ChannelEvent. If eventName is omitted, returns all registered listeners. Returns null if there are no matching listeners.

Parameters

The listeners() method takes the following parameters:

eventNameoptionalChannelEvent
The channel event to filter listeners by.

Returns

null | channelEventCallback[]

Returns an array of the registered listener functions, or null if there are none.

Wait for a channel state

channel.whenState(targetState: ChannelState): Promise<ChannelStateChange | null>

If the channel 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 channel transitions to the given state.

Parameters

The whenState() method takes the following parameters:

targetStaterequiredChannelState
The channel state to wait for.

Returns

Promise<ChannelStateChange | null>

Returns a promise. If the channel is already in the given state, resolves to null. Otherwise resolves with the ChannelStateChange when the channel next transitions to that state.

Get message history

channel.history(params?: RealtimeHistoryParams): Promise<PaginatedResult<InboundMessage>>

Retrieve a PaginatedResult of historical messages for this channel. If the channel is configured to persist messages, message history is available for the persistence duration configured for your account. If not, messages are only retained in memory by the Ably service for two minutes.

JavaScript

1

2

const page = await channel.history({ limit: 50, direction: 'backwards' });
page.items.forEach((message) => console.log(message.data));

Parameters

The history() method takes the following parameters:

paramsoptionalRealtimeHistoryParams
Query parameters to filter and control retrieval.

Returns

Promise<PaginatedResult<InboundMessage>>

Returns a promise. The promise is fulfilled with a PaginatedResult containing an array of Message objects, or rejected with an ErrorInfo object.

Get all versions of a message

channel.getMessageVersions(serialOrMessage: string | Message, params?: RealtimeHistoryParams): Promise<PaginatedResult<Message>>

Retrieve all historical versions of a message identified by its serial, ordered by version. This includes the original message and all subsequent updates and delete operations. Requires the history capability.

Parameters

The getMessageVersions() method takes the following parameters:

serialOrMessagerequiredString or Message
Either the serial identifier string of the message whose versions are to be retrieved, or a Message object containing a populated serial field.
paramsoptionalRealtimeHistoryParams
Query parameters to filter and control retrieval.

Returns

Promise<PaginatedResult<Message>>

Returns a promise. The promise is fulfilled with a PaginatedResult of message versions, or rejected with an ErrorInfo object.