fetchNext method

Future<List<Conversation>> fetchNext({
  1. ConversationFetchListener? listener,
  2. dynamic onSuccess(
    1. List<Conversation> message
    )?,
  3. dynamic onError(
    1. CometChatException excep
    )?,
})

Returns a list of Conversation object fetched after putting the filters.

Android Reference: ConversationsRequest.fetchNext() Offline (opt-in, additive): pass listener for the two-phase read — onCachedConversations (instant local page) → onServerConversations (authoritative; replacement is what drives removals) / onError.

Backward compatibility: the cache phase is listener-only, so a legacy caller's behavior — including error semantics — is unchanged whether offline is enabled or not.

The cache phase fires on every page, from the cache's own cursor (BEH-READ-12): page 2 is the cached rows after page 1's, never page 1 again — offline, where the server page number never advances, too.

Implementation

Future<List<Conversation>> fetchNext({
  ConversationFetchListener? listener,
  Function(List<Conversation> message)? onSuccess,
  Function(CometChatException excep)? onError,
}) async {
  var cacheDelivered = false;
  try {
    final effectiveLimit = limit ?? defaultLimit;
    if (effectiveLimit <= 0) {
      final error = CometChatException(
        'ERR_NON_POSITIVE_LIMIT',
        'Limit must be a positive number',
        'Limit must be a positive number',
      );
      _deliverConversationError(error, listener, onError, false);
      return [];
    }

    if (effectiveLimit > maxLimit) {
      final error = CometChatException(
        'ERR_LIMIT_EXCEEDED',
        'Limit cannot exceed $maxLimit',
        'Limit cannot exceed $maxLimit',
      );
      _deliverConversationError(error, listener, onError, false);
      return [];
    }

    // Phase 1 — cache (listener-only), on every page, from the cache's own
    // cursor (BEH-READ-12).
    if (listener != null && !_appSetStartPage) {
      try {
        final cached = await _cachedPage(limit: effectiveLimit);
        if (cached != null) {
          cacheDelivered = true;
          listener.onCachedConversations(cached);
        }
      } catch (_) {
        // Non-fatal; the server phase still runs.
      }
    }

    // With offline on, a two-phase read past the last page still asks the
    // server for that page (BEH-READ-05 / BEH-READ-09a, R105): an empty
    // answer is the end of the list, no answer is the not-connected error.
    // The synthesized empty server page below stays for legacy callers and
    // offline OFF — and for a `pinnedBy` list: its server answer is
    // reconciled as the COMPLETE pinned set of its scope (BEH-CPIN-03), so an
    // empty past-the-end page would clear every cached pin. R120 for pinned
    // lists belongs to phase 10.
    final readsPastTheEnd =
        listener != null &&
        (pinnedBy?.isEmpty ?? true) &&
        OfflineReadCache.available;
    if ((_nextPage == -1 || _nextPage <= _totalPages || readsPastTheEnd) &&
        !_inProgress) {
      _inProgress = true;

      final sdk = SdkRegistry.getInstance();

      // Captured as the request goes out: a page answered after this
      // session ended is never written (BEH-SYNC-06).
      final issuedIn = OfflineRuntime.instance.readSession;
      final firstPage = _nextPage == -1;
      // R156: the cached rows as they stand when the request is sent, so the
      // purge spares every row written while it is in flight.
      final atDispatch = firstPage && _omissionEligible
          ? await OfflineReadCache.conversationsAtDispatch(issuedIn)
          : null;
      final result = await sdk.conversations.getConversations(
        limit: effectiveLimit,
        page: _nextPage != -1 ? _nextPage : null,
        conversationType: conversationType,
        withUserAndGroupTags: withUserAndGroupTags,
        withTags: withTags,
        tags: tags,
        userTags: userTags,
        groupTags: groupTags,
        includeBlockedUsers: includeBlockedUsers,
        withBlockedInfo: withBlockedInfo,
        searchKeyword: searchKeyword,
        unread: unread,
        hideAgentic: hideAgentic,
        onlyAgentic: onlyAgentic,
        pinnedBy: pinnedBy,
      );

      _totalPages = result.totalPages;
      _currentPage = result.currentPage;
      _nextPage = _currentPage + _pageOffset;

      key = _currentPage.toString();
      _inProgress = false;

      // Offline: warm the cache with this server page (no-op when disabled).
      await _persistToCache(
        result.conversations,
        issuedIn,
        firstPage: firstPage,
        hasMore: result.currentPage < result.totalPages,
        atDispatch: atDispatch,
      );

      // Listener wins — never both.
      if (listener != null) {
        listener.onServerConversations(result.conversations);
      } else if (onSuccess != null) {
        onSuccess(result.conversations);
      }
      return result.conversations;
    } else {
      if (listener != null) {
        listener.onServerConversations([]);
      } else if (onSuccess != null) {
        onSuccess([]);
      }
      return [];
    }
  } on sdk_errors.SdkException catch (sdkEx) {
    _inProgress = false;
    final cometChatEx = CometChatException(
      sdkEx.code,
      sdkEx.details ?? sdkEx.message,
      sdkEx.message,
    );
    _deliverConversationError(cometChatEx, listener, onError, cacheDelivered);
  } catch (e) {
    _inProgress = false;
    final cometChatEx = CometChatException(
      ErrorCode.errorUnhandledException,
      e.toString(),
      e.toString(),
    );
    _deliverConversationError(cometChatEx, listener, onError, cacheDelivered);
  }
  return [];
}