@ably/chat - v1.1.1
    Preparing search index...

    Interface MessageSubscriptionResponse

    A response object that allows you to control a message subscription.

    interface MessageSubscriptionResponse {
        unsubscribe: () => void;
        historyBeforeSubscribe(
            params: Omit<HistoryParams, "orderBy">,
        ): Promise<PaginatedResult<Message>>;
    }

    Hierarchy (View Summary)

    Index

    Properties

    unsubscribe: () => void

    This method should be called when the subscription is no longer needed, it will make sure no further events will be sent to the subscriber and that references to the subscriber are cleaned up.

    Methods

    • Get the previous messages that were sent to the room before the listener was subscribed. This can be used to populate a room on initial subscription or to refresh local state after a discontinuity event.

      NOTE:

      • If the client experiences a discontinuity event (i.e. the connection was lost and could not be resumed), the starting point of historyBeforeSubscribe will be reset.
      • Calls to historyBeforeSubscribe will then wait for continuity to be restored before resolving.
      • Once continuity is restored, the subscription point will be set to the beginning of this new period of continuity. To ensure that no messages are missed (or updates/deletes), you should call historyBeforeSubscribe after any period of discontinuity to re-populate your local state.

      Parameters

      • params: Omit<HistoryParams, "orderBy">

        Parameters for the history query.

      Returns Promise<PaginatedResult<Message>>

      A promise that resolves with the paginated result of messages, in newest-to-oldest order.

      import * as Ably from 'ably';
      import { ChatClient, ChatMessageEventType } from '@ably/chat';

      const chatClient: ChatClient; // existing ChatClient instance
      const room = await chatClient.rooms.get('general-chat');

      // Local message state
      let localMessages: Message[] = [];

      const updateLocalMessageState = (messages: Message[], message:Message): void => {
      // Find existing message in local state
      const existingIndex = messages.findIndex(m => m.serial === message.serial);
      if (existingIndex === -1) {
      // New message, add to local state
      messages.push(message);
      } else {
      // Existing message, update local state
      messages[existingIndex] = messages[existingIndex].with(message);
      }
      // Messages should be ordered by serial
      messages.sort((a, b) => a.serial < b.serial ? -1 : (b.serial < a.serial ? 1 : 0));
      };


      // Subscribe a listener to message events
      const subscription = room.messages.subscribe((event) => {
      console.log(`Message ${event.type}:`, event.message.text);
      updateLocalMessageState(localMessages, event.message);
      });

      // Attach to the room to start receiving message events
      await room.attach();

      // Get historical messages before subscription
      try {
      const history = await subscription.historyBeforeSubscribe({ limit: 50 });
      console.log(`Retrieved ${history.items.length} historical messages`);

      // Process historical messages
      history.items.forEach(message => {
      console.log(`Historical: ${message.text} from ${message.clientId}`);
      updateLocalMessageState(localMessages, message);
      });
      } catch (error) {
      console.error('Failed to retrieve message history:', error);
      }
      // Subscribe a listener to message events as before
      const { historyBeforeSubscribe } = // subscribed listener response

      // Subscribe to discontinuity events on the room
      room.onDiscontinuity(async (reason) => {
      console.warn('Discontinuity detected:', reason);
      // Clear local state and re-fetch messages
      localMessages = []
      try {
      // Fetch messages before the new subscription point
      const history = await subscription.historyBeforeSubscribe({ limit: 100 });

      // Merge each message into local state
      history.items.forEach(message => {
      updateLocalMessageState(localMessages, message);
      });

      console.log(`Refreshed local state with ${localMessages.length} messages`);
      } catch (error) {
      console.error('Failed to refresh messages after discontinuity:', error);
      }
      });

      // Attach to the room to start receiving events
      await room.attach();