fetchNext method

Future<List<Group>> fetchNext({
  1. required dynamic onSuccess(
    1. List<Group> groupList
    )?,
  2. required dynamic onError(
    1. CometChatException excep
    )?,
  3. GroupFetchListener? listener,
})

Returns list of Group object fetched after putting the filters.

Android Reference: GroupsRequest.fetchNext()

Implementation

Future<List<Group>> fetchNext({
  required Function(List<Group> groupList)? onSuccess,
  required Function(CometChatException excep)? onError,
  GroupFetchListener? listener,
}) async {
  try {
    if (limit > _maxLimit) {
      final error = CometChatException(
        ErrorCode.errorLimitExceeded,
        'Limit cannot exceed $_maxLimit',
        'Limit cannot exceed $_maxLimit',
      );
      if (onError != null) onError(error);
      listener?.onError(error);
      return [];
    }

    if (limit <= 0) {
      final error = CometChatException(
        ErrorCode.errorNonPositiveLimit,
        'Limit must be a positive number',
        'Limit must be a positive number',
      );
      if (onError != null) onError(error);
      listener?.onError(error);
      return [];
    }

    // Past the end of history a two-phase read with offline running still
    // asks the server: an empty answer ends the list, no answer is the
    // not-connected error (BEH-READ-05, BEH-READ-09a, R105). A legacy caller,
    // or any caller with offline off, keeps the empty page it always got
    // (BEH-AUTH-05).
    if ((listener == null || OfflineRuntime.instance.store == null) &&
        _nextPage > _totalPages &&
        _totalPages != 0) {
      if (onSuccess != null) onSuccess([]);
      listener?.onServerGroups(const []);
      return [];
    }

    // A concurrent fetch answers an empty success, settling the listener
    // too, so a listener-only caller is never left waiting (BEH-SNAP-14).
    if (_inProgress) {
      if (onSuccess != null) onSuccess([]);
      listener?.onServerGroups(const []);
      return [];
    }
    // Set before the cache phase: a fetch called while this one is in
    // flight fires no cache phase and leaves the replay index alone
    // (BEH-SNAP-14).
    _inProgress = true;

    // Phase 1 — replay a recorded page for this query. The snapshot's
    // replay index is independent of the request's page cursor, so a
    // replay never advances the server cursor.
    if (listener != null) {
      final cached = await _snapshots.cachedPhase(Group.fromMap);
      if (cached != null) listener.onCachedGroups(cached);
    }

    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 result = await sdk.groups.getGroups(
      limit: limit,
      token: _cursor != 0 ? _cursor : null,
      page: _nextPage > 0 ? _nextPage : null,
      searchKeyword: searchKeyword,
      joinedOnly: joinedOnly,
      tags: tags,
      withTags: withTags,
    );

    if (result.pagination != null) {
      if (result.pagination!.totalPages != null) {
        _totalPages = result.pagination!.totalPages!;
      }
      if (result.pagination!.currentPage != null) {
        _currentPage = result.pagination!.currentPage!;
        _nextPage = _currentPage + _pageOffset;
      }
    }

    if (result.nextToken != null) {
      _cursor = result.nextToken!;
      key = _cursor.toString();
    }

    final groups = result.groups;

    // Record before delivering, so a caller that re-reads immediately sees
    // the same page.
    await _snapshots.recordEntities(
      groups,
      hasNext: _totalPages != 0 && _nextPage <= _totalPages,
      issuedIn: issuedIn,
      toJson: (g) => (g as Group).toJson(),
    );

    // Held through the record step, so a fetch landing during it cannot
    // replay the page about to be delivered (BEH-SNAP-14); cleared before
    // the callbacks, so a fetch made from one of them is a new fetch.
    _inProgress = false;
    if (onSuccess != null) onSuccess(groups);
    listener?.onServerGroups(groups);
    return groups;
  } on SdkException catch (sdkEx) {
    _inProgress = false;
    final cometChatEx = CometChatException(
      sdkEx.code,
      sdkEx.details ?? sdkEx.message,
      sdkEx.message,
    );
    if (onError != null) onError(cometChatEx);
    listener?.onError(cometChatEx);
  } catch (e) {
    _inProgress = false;
    final cometChatEx = CometChatException(
      ErrorCode.errorUnhandledException,
      e.toString(),
      e.toString(),
    );
    if (onError != null) onError(cometChatEx);
    listener?.onError(cometChatEx);
  }
  return [];
}