putIfAbsent method

  1. @override
Future<bool> putIfAbsent(
  1. String key,
  2. dynamic value,
  3. {Duration? expiryDuration}
)
override

Associates the specified key with the given value if not already associated with a value.

  • key: key with which the specified value is to be associated
  • value: value to be associated with the specified key

Returns true if a value was set.

Implementation

@override
Future<bool> putIfAbsent(String key, dynamic value,
    {Duration? expiryDuration}) {
  // Try to get the entry from the cache
  return _getStorageEntry(key).then((entry) {
    final now = clock.now();
    var expired = entry != null && entry.isExpired(now);

    // If the entry exists on cache but is already expired we remove it first
    final pre = expired
        ? _removeStorageEntry(key, ExpiredEntryEvent(this, entry!))
        : Future.value();

    // If the entry is expired or non existent
    if (entry == null || expired) {
      return pre.then((_) => _putEntry(key, value, now, expiryDuration));
    }

    return Future.value(false);
  });
}