loadNextPage method

Future<void> loadNextPage(
  1. K key
)

Loads next page of pageable data and updates cache.

Throws InconsistentPageDataException if duplicatesDetectionEnabled and detected that new page has items that already loaded on a previous page (it means that data on the server was changed and we need to reload all items).

Implementation

Future<void> loadNextPage(K key) async {
  if (_loading) return;
  _loading = true;
  _logger?.trace(LoggerLevel.debug, 'PageableRes: Load next page requested');
  try {
    final currentData = await _cachedResource.getCachedValue(key);
    if (currentData?.loadedAll == true) {
      _logger?.trace(
          LoggerLevel.debug, 'PageableRes: All items are already loaded');
      return;
    }
    final nextPage = currentData?.nextPage ?? 1;
    _logger?.trace(
        LoggerLevel.debug, 'PageableRes: Load next page [$nextPage]');

    final nextPageResponse = await _loadPage(key, nextPage, pageSize);
    final loadedItems = nextPageResponse.items;

    return _cachedResource.updateCachedValue(key, (data) {
      if (data != currentData) {
        _logger?.trace(LoggerLevel.warning,
            'PageableRes: Cached data was changed during loading next page => ignore next page data');
        return data;
      }
      final oldItems = data?.items ?? <V>[];
      if (duplicatesDetectionEnabled) {
        _assertIntersectedItems(oldItems, loadedItems);
      }
      checkConsistency(data, nextPageResponse);
      return _pageableDataFactory.create(
        nextPage:
            isLoadedAll(nextPageResponse, pageSize) ? null : nextPage + 1,
        items: oldItems + loadedItems,
        meta: buildMeta(data, nextPageResponse),
      );
    });
  } catch (error, trace) {
    _logger?.trace(LoggerLevel.error, 'PageableRes: Error loading next page',
        error, trace);
    rethrow;
  } finally {
    _loading = false;
  }
}