put method

Future<void> put(
  1. T item, {
  2. bool ignoreBounds = false,
  3. bool store = true,
})

Adds the provided item to the items.

item will be added if it is within the bounds of the stored items.

If store is false, then the item will be only added to the items and won't be put to the provider.

Implementation

Future<void> put(
  T item, {
  bool ignoreBounds = false,
  bool store = true,
}) async {
  if (_disposed) {
    return;
  }

  Log.debug('put($item)', '$runtimeType');

  // Bypasses the bounds check.
  //
  // Intended to be used to forcefully add items, e.g. when items are
  // migrating from one source to another.
  bool put = ignoreBounds;

  if (!put) {
    await _itemsGuard.protect(() async {
      // Wait for [items] fetching before putting a new one.
      await _guard.protect(() async => null);
      await _nextGuard.protect(() async => null);
      await _previousGuard.protect(() async => null);

      if (items.isEmpty) {
        put = hasNext.isFalse && hasPrevious.isFalse;
      } else if (compare?.call(item, items.last) == 1) {
        put = hasNext.isFalse;
      } else if (compare?.call(item, items.first) == -1) {
        put = hasPrevious.isFalse;
      } else {
        put = true;
      }
    });
  }

  if (put) {
    items[onKey(item)] = item;
  }

  if (store) {
    await provider.put([item], compare: put ? null : compare);
  }
}