getAndPut method Null safety

  1. @override
Future<T?> getAndPut(
  1. String key,
  2. T value,
  3. {CacheEntryDelegate<T>? delegate}
)
override

Associates the specified value with the specified key in this cache, returning an existing value if one existed. If the cache previously contained a mapping for the key, the old value is replaced by the specified value.

  • key: key with which the specified value is to be associated
  • value: value to be associated with the specified key
  • delegate: provides the caller a way of changing the CacheEntry before persistence

The previous value is returned, or null if there was no value associated with the key previously.

Implementation

@override
Future<T?> getAndPut(String key, T value, {CacheEntryDelegate<T>? delegate}) {
  // #region Statistics
  Stopwatch? watch;
  Future<T?> Function(T? value) posGetPut = (T? value) => Future.value(value);
  if (statsEnabled) {
    watch = clock.stopwatch()..start();
    posGetPut = (T? value) {
      if (value == null) {
        stats.increaseMisses();
      } else {
        stats.increaseGets();
      }
      stats.increasePuts();
      if (watch != null) {
        int elapsed = watch.elapsedMicroseconds;
        stats.addGetTime(elapsed);
        stats.addPutTime(elapsed);
        watch.stop();
      }

      return Future.value(value);
    };
  }
  // #endregion

  return _primary.getAndPut(key, value).then((primaryValue) {
    if (primaryValue == null) {
      return _secondary.getAndPut(key, value);
    }

    return _secondary.put(key, value).then((_) => value);
  }).then(posGetPut);
}