applyToItem method

Future<bool> applyToItem(
  1. TIdentifier id,
  2. dynamic callback(
    1. Future<TValue> value
    )
)

Returns true and calls callback if there is a cached, unreleased TValue associated with id; returns false otherwise.

This does not perform a get or getAsync, and as a result, will not affect retention or removal of a TValue pair from the cache.

Any TIdentifier TValue pair removals will wait for the Future returned by the call to callback before emitting didRemove events.

If the Cache isOrWillBeDisposed then a StateError is thrown.

Implementation

Future<bool> applyToItem(
    TIdentifier id, dynamic callback(Future<TValue> value)) {
  _log.finest('applyToItem id: $id');
  _throwWhenDisposed('applyToItem');
  if (_isReleased[id] != false || _cache[id] == null) {
    return Future<bool>.value(false);
  }

  final callBackResult = callback(_cache[id]!);
  if (callBackResult is Future<dynamic>) {
    // In this case we're only interested in the computation being done or not
    // done, not in the result
    final errorlessCallbackResult =
        callBackResult.then((_) {}, onError: (_) {});

    _applyToItemCallBacks.putIfAbsent(id, () => <Future<dynamic>>[]);
    _applyToItemCallBacks[id]!.add(errorlessCallbackResult);

    errorlessCallbackResult.whenComplete(() {
      _applyToItemCallBacks[id]!.remove(errorlessCallbackResult);
      if (_applyToItemCallBacks[id]!.isEmpty) {
        _applyToItemCallBacks.remove(id);
      }
    });

    // Return future that will complete with either true or the error
    // generated from callback
    return callBackResult.then((_) => true);
  }
  return Future<bool>.value(true);
}