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.
1
const channel = realtime.channels.get('all-gas-ion');Properties
The RealtimeChannel interface has the following properties:
nameStringstateChannelStateerrorReasonErrorInfo or UndefinedpresenceRealtimePresenceRealtimePresence object for this channel.pushPushChannelPushChannel object for this channel.annotationsRealtimeAnnotationsRealtimeAnnotations object for this channel, used to publish, delete, retrieve, and subscribe to annotations on messages.paramsRecord<String, String>modesResolvedChannelMode[]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.
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
attachedand it later becomesdetachedorfailed, the listener is still invoked when the channel reattaches and a message is received. Listeners are only removed by callingunsubscribe()or when the channel is released usingchannels.release(). - If an exception is thrown in a listener and bubbles up to the event emitter, it is caught and logged at
errorlevel, so as not to affect other listeners for the same event.
Parameters
The subscribe() method takes the following parameters:
eventoptionalStringeventsoptionalString[]filteroptionalMessageFilterlisteneroptionalFunctionMessage. 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.
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:
namerequiredStringdatarequiredAnynull. If sending binary data, that binary should be the entire payload; an object with a binary field within it may not be correctly encoded.optionsoptionalObjectReturns
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 Nullnull 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:
serial of the message being updated.operationoptionalMessageOperationoptionsoptionalObjectReturns
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 Nullnull 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:
serial of the target message.operationoptionalMessageOperationoptionsoptionalObjectReturns
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:
serial of the message being deleted.operationoptionalMessageOperationoptionsoptionalObjectReturns
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:
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): voidRemove the given listener for the specified event.
channel.unsubscribe(events: string[], listener: messageCallback): voidRemove the given listener from all events in the array.
channel.unsubscribe(event: string): voidRemove all listeners registered for the specified event.
channel.unsubscribe(events: string[]): voidRemove all listeners registered for any event in the array.
channel.unsubscribe(filter: MessageFilter, listener?: messageCallback): voidRemove the listener registered for the specified filter, or all listeners for the filter if listener is omitted.
channel.unsubscribe(listener: messageCallback): voidRemove the given listener from all events.
channel.unsubscribe(): voidRemove all message listeners on this channel.
1
channel.unsubscribe();Parameters
The unsubscribe() method takes the following parameters:
eventoptionalStringeventsoptionalString[]filteroptionalMessageFilterlisteneroptionalFunctionAttach 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.
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.
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.
1
await channel.setOptions({ cipher: { key } });Parameters
The setOptions() method takes the following parameters:
optionsrequiredChannelOptionsReturns
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): voidRegister a listener for a single channel event.
channel.on(events: ChannelEvent[], listener: channelEventCallback): voidRegister a listener for any of an array of channel events.
channel.on(listener: channelEventCallback): voidRegister 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.
1
2
3
channel.on('attached', (stateChange) => {
console.log('Now attached');
});Parameters
The on() method takes the following parameters:
eventoptionalChannelEventeventsoptionalChannelEvent[]listenerrequiredchannelEventCallbackevent nor events is supplied, it fires for every event.Register a one-time channel state listener
channel.once(event: ChannelEvent, listener: channelEventCallback): voidRegister a one-time listener for a single channel event. It is invoked the next time that event occurs, then removed.
channel.once(listener: channelEventCallback): voidRegister 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.
1
await channel.once('attached');Parameters
The once() method takes the following parameters:
eventoptionalChannelEventlisteneroptionalchannelEventCallbackReturns
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): voidRemove the given listener for a specific channel event.
channel.off(listener: channelEventCallback): voidRemove the given listener from all channel events.
channel.off(): voidRemove all channel state listeners.
1
channel.off();Parameters
The off() method takes the following parameters:
eventoptionalChannelEventlisteneroptionalchannelEventCallbackGet 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:
eventNameoptionalChannelEventReturns
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:
targetStaterequiredChannelStateReturns
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.
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:
paramsoptionalRealtimeHistoryParamsReturns
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:
Returns
Promise<PaginatedResult<Message>>
Returns a promise. The promise is fulfilled with a PaginatedResult of message versions, or rejected with an ErrorInfo object.