loadMore method

Future<void> loadMore()

Loads next channel lists, depending on the GroupChannelListQueryOrder set in the current collection.

Implementation

Future<void> loadMore() async {
  if (_isDisposed) {
    throw InvalidCollectionDisposedException();
  }

  sbLog.i(StackTrace.current, 'loadMore()');

  _isLoading = true;
  _isLoadedOnce = true;

  //+ [DBManager]
  List<GroupChannel> localChannels = [];
  if (_chat.dbManager.isEnabled()) {
    final info = await _chat.dbManager.getChannelInfo();
    if (info != null && info.isChannelBackSyncCompleted) {
      final channels = await _chat.dbManager
          .getGroupChannels(query: _query, offset: _offset);
      if (channels.isNotEmpty) {
        localChannels.addAll(channels);
      }

      if (_query.limit == localChannels.length) {
        final channels = await _chat.dbManager
            .getGroupChannels(query: _query, offset: _offset + _query.limit);
        _hasMore = channels.isNotEmpty;
      } else {
        _hasMore = false;
      }

      if (localChannels.isNotEmpty) {
        await _chat.collectionManager.sendEventsToGroupChannelCollection(
          channelCollection: this,
          eventSource: CollectionEventSource.channelCacheLoadMore,
          addedChannels: localChannels,
        );
      }
    }
  }
  //- [DBManager]

  try {
    if (localChannels.isNotEmpty) {
      //+ [DBManager]
      if (_chat.dbManager.isEnabled()) {
        _offset += localChannels.length; // Check
      }
      //- [DBManager]
    } else {
      final channels = await _query.next();

      _hasMore = _query.hasNext;

      if (channels.isNotEmpty) {
        //+ [DBManager]
        if (_chat.dbManager.isEnabled()) {
          final List<GroupChannel> addedChannels = [...channels];
          final Set<String> deletedChannelUrls =
              localChannels.map((e) => e.channelUrl).toSet();
          deletedChannelUrls.addAll(
              channelList.sublist(_fetchedCount).map((e) => e.channelUrl));

          _fetchedCount += channels.length;
          _offset = _fetchedCount;

          await _chat.collectionManager.sendEventsToGroupChannelCollection(
            channelCollection: this,
            eventSource: CollectionEventSource.channelLoadMore,
            addedChannels: addedChannels,
            deletedChannelUrls: deletedChannelUrls.toList(),
          );
        }
        //- [DBManager]
        else {
          await _chat.collectionManager.sendEventsToGroupChannelCollection(
            channelCollection: this,
            eventSource: CollectionEventSource.channelLoadMore,
            addedChannels: channels,
          );
        }
      }
    }
  } catch (e) {
    //+ [DBManager]
    if (_chat.dbManager.isEnabled()) {
      _offset += localChannels.length; // Check
    }
    //- [DBManager]
    else {
      rethrow;
    }
  }

  _isLoading = false;
}