fetchNext method

Future<List<MessageThread>> fetchNext({
  1. ThreadsFetchListener? listener,
  2. dynamic onSuccess(
    1. List<MessageThread> threads
    )?,
  3. dynamic onError(
    1. CometChatException excep
    )?,
})

Fetches the next page of threads.

Resolves [] once the list is exhausted. Rejects with ERR_REQUEST_IN_PROGRESS if a fetch is already in flight on this request.

Implementation

Future<List<MessageThread>> fetchNext({
  ThreadsFetchListener? listener,
  Function(List<MessageThread> threads)? onSuccess,
  Function(CometChatException excep)? onError,
}) async {
  // Phase 1 — cache. Listener-only, so a legacy caller sees exactly today's
  // behaviour (BEH-THR-03). The store is read in its own sort order with this
  // request's own cursor, scoped to uid/guid when one is set; an empty page
  // means the end of the cached WINDOW, never the end of the list.
  if (listener != null) {
    try {
      final page = await _threadCachePage();
      if (page != null) {
        _storeCursor = page.nextCursor;
        // An empty STORE page is the end of the stored window. An empty
        // snapshot page is only this fetch's miss: the next fetch may
        // replay a later recorded page, so it never closes the phase.
        if (page.isEmpty && participatedByMe) _storeExhausted = true;
        listener.onCachedThreads(page.threads);
      }
      _storeSeqAtDispatch =
          await OfflineRuntime.instance.store?.currentStoreSeq() ?? 0;
    } catch (_) {
      // Non-fatal; the server phase still runs.
    }
  }
  try {
    // Validate before any network call (§5.3).
    if (limit < 1 || limit > maxLimit) {
      final error = CometChatException(
        'ERR_INVALID_LIMIT',
        'Limit must be between 1 and $maxLimit',
        'Limit must be between 1 and $maxLimit',
      );
      _deliverError(error, listener, onError);
      return [];
    }
    if (guid != null && guid!.isNotEmpty && uid != null && uid!.isNotEmpty) {
      final error = CometChatException(
        'ERR_INVALID_FILTER',
        'setGuid and setUid are mutually exclusive — set only one',
        'setGuid and setUid are mutually exclusive — set only one',
      );
      _deliverError(error, listener, onError);
      return [];
    }

    // A read past the end, two-phase with offline running, still makes its
    // request (BEH-READ-05, R105/R120): the cursor already points past the
    // last row, and only threads this request has not delivered go out — an
    // empty answer is the end, no answer the not-connected error. A legacy
    // caller, or offline off, keeps the empty page (BEH-AUTH-05).
    final readsPastTheEnd =
        _exhausted &&
        listener != null &&
        OfflineRuntime.instance.store != null;
    if (_exhausted && !readsPastTheEnd) {
      _deliverThreads(const [], listener, onSuccess);
      return [];
    }
    if (_inProgress) {
      final error = CometChatException(
        'ERR_REQUEST_IN_PROGRESS',
        'A fetch is already in progress on this ThreadsRequest',
        'A fetch is already in progress on this ThreadsRequest',
      );
      _deliverError(error, listener, onError);
      return [];
    }

    _inProgress = true;
    try {
      if (readsPastTheEnd) {
        // Delivered, never written or recorded, and the cursor stays (R120).
        final page = await _fetchPage();
        final fresh = page.threads
            .where((thread) => !_seenIds.contains(thread.parentMessageId))
            .toList();
        _seenIds.addAll(fresh.map((thread) => thread.parentMessageId));
        _deliverThreads(fresh, listener, onSuccess);
        return fresh;
      }
      // 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 fresh = await _fetchFreshRows();
      // The page is written through BEFORE it is delivered (BEH-THR-03), so a
      // listener that re-reads the store from its own callback sees it.
      await _writeThreadPage(fresh, issuedIn);
      _deliverThreads(fresh, listener, onSuccess);
      return fresh;
    } finally {
      _inProgress = false;
    }
  } on sdk_errors.SdkException catch (sdkEx) {
    final cometChatEx = CometChatException(
      sdkEx.code,
      sdkEx.details ?? sdkEx.message,
      sdkEx.message,
    );
    _deliverError(cometChatEx, listener, onError);
  } catch (e) {
    final cometChatEx = CometChatException(
      ErrorCode.errorUnhandledException,
      e.toString(),
      e.toString(),
    );
    _deliverError(cometChatEx, listener, onError);
  }
  return [];
}