putIfAbsent method

Future<ByteData> putIfAbsent(
  1. Object key,
  2. Future<ByteData> loader()
)

Returns the previously cached ByteData for the given key, if available; if not, calls the given callback to obtain it first. In either case, the key is moved to the "most recently used" position.

The arguments must not be null. The loader cannot return null.

Implementation

Future<ByteData> putIfAbsent(
  Object key,
  Future<ByteData> Function() loader,
) {
  // Return pending result if the loader is already called.
  if (_pending.containsKey(key)) {
    return _pending[key]!;
  }

  ByteData? cachedResult = _cache[key];
  if (cachedResult != null) {
    // Move the cached item to the end to mark it as recently used.
    _cache.remove(key);
    _cache[key] = cachedResult;
    return SynchronousFuture<ByteData>(cachedResult);
  }

  // Call the loader to get new data.
  Future<ByteData> futureData = loader();
  _pending[key] = futureData;

  futureData.then((ByteData data) {
    _pending.remove(key);
    _add(key, data);
  });

  return futureData;
}