getAndRemove method

  1. @override
Future<T?> getAndRemove(
  1. String key
)
override

Removes the entry for a key only if currently mapped to some value.

  • key: key with which the specified value is associated

Returns the value if exists or null if no mapping existed for this key

Implementation

@override
Future<T?> getAndRemove(String key) {
  // Current time
  final now = clock.now();
  // #region Statistics
  Stopwatch? watch;
  Future<CacheEntry?> Function(CacheEntry? entry) posGet =
      (CacheEntry? entry) => Future.value(entry);
  Future<T?> Function(CacheEntry entry) posRemove =
      (CacheEntry entry) => Future<T?>.value(entry.value);
  if (statsEnabled) {
    watch = clock.stopwatch()..start();
    posGet = (CacheEntry? entry) {
      if (entry == null || entry.isExpired(now)) {
        stats.increaseMisses();
      } else {
        stats.increaseGets();
      }
      if (watch != null) {
        stats.addGetTime(watch.elapsedMicroseconds);
      }

      return Future.value(entry);
    };
    posRemove = (CacheEntry entry) {
      stats.increaseRemovals();
      if (watch != null) {
        stats.addRemoveTime(watch.elapsedMicroseconds);
        watch.stop();
      }

      return Future<T?>.value(entry.value);
    };
  }
  // #endregion

  // Try to get the entry from the cache
  return _getStorageEntry(key).then(posGet).then((entry) {
    if (entry != null) {
      // The entry exists on cache
      // Let's check if it is expired
      if (entry.isExpired(now)) {
        // If expired let's remove from cache, send an expired event and return
        // null
        return _removeStorageEntry(
                key, CacheEntryExpiredEvent<T>(this, entry.info))
            .then((_) => posRemove(entry));
      } else {
        // If not expired let's remove from cache, send a removed event and
        // return the value
        return _removeStorageEntry(
                key, CacheEntryRemovedEvent<T>(this, entry.info))
            .then((_) => posRemove(entry));
      }
    }

    return Future<T?>.value();
  });
}