load method

  1. @override
Future<LocalCollectionModel<T>> load()
override

Retrieves data and updates the data in the model.

You will be notified of model updates at the time they are retrieved.

In addition, the updated Resuult can be obtained at the stage where the loading is finished.

Implementation

@override
Future<LocalCollectionModel<T>> load() async {
  if (_completer != null) {
    await future;
    return this;
  }
  _completer = Completer<void>();
  try {
    await onLoad();
    bool notify = false;
    _query ??= _LocalStoreCollectionQuery(
      path: path,
      callback: _handledOnUpdate,
      filter: parameters.isEmpty
          ? null
          : (data) => CollectionQuery._filter(parameters, data),
      origin: this,
    );
    LocalDatabase._db.addCollectionListener(_query!);
    final data = await LocalDatabase._db.loadCollection(_query!);
    if (isNotEmpty) {
      clear();
      notify = true;
    }
    if (data.isNotEmpty) {
      notify = true;
      final addData = <T>[];
      _rawEntries = CollectionQuery._sort(
        parameters,
        List.from(data!.entries),
      );
      int i = 0;
      final limit = CollectionQuery._limitCount(parameters);
      for (final tmp in _rawEntries) {
        if (tmp.key.isEmpty || tmp.value is! DynamicMap) {
          continue;
        }
        if (limit != null && i >= limit) {
          continue;
        }
        final value = createDocument("${path.trimQuery()}/${tmp.key}");
        value.value = value.fromMap(value.filterOnLoad(Map.from(tmp.value)));
        addData.add(value);
        i++;
      }
      addAll(addData);
    }
    if (notify) {
      notifyListeners();
    }
    await onDidLoad();
    _completer?.complete();
    _completer = null;
  } catch (e) {
    _completer?.completeError(e);
    _completer = null;
  } finally {
    _completer?.complete();
    _completer = null;
  }
  return this;
}