getAndPut method

  1. @override
Future<T?> getAndPut(
  1. String key,
  2. T value, {
  3. VaultEntryDelegate<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 VaultEntry 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, {VaultEntryDelegate<T>? delegate}) {
  // Current time
  final now = clock.now();
  // #region Statistics
  Stopwatch? watch;
  Future<VaultEntry?> Function(VaultEntry? entry) posGet =
      (VaultEntry? entry) => Future.value(entry);
  Future<T?> Function(T? value) posPut =
      (T? value) => Future<T?>.value(value);
  if (statsEnabled) {
    watch = clock.stopwatch()..start();
    posGet = (VaultEntry? entry) {
      stats.increaseGets();

      if (watch != null) {
        stats.addGetTime(watch.elapsedMicroseconds);
      }

      return Future.value(entry);
    };
    posPut = (T? value) {
      stats.increasePuts();

      if (watch != null) {
        stats.addPutTime(watch.elapsedMicroseconds);
        watch.stop();
      }

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

  // Try to get the entry from the vault
  return _getStorageEntry(key).then(posGet).then((entry) {
    // If the entry does not exist
    if (entry == null) {
      return _newEntry(_entryBuilder(key, value, now))
          .then((_) => posPut(null));
    } else {
      return _replaceEntry(entry.info, value, now)
          .then((_) => posPut(entry.value));
    }
  });
}