dart-neats icon indicating copy to clipboard operation
dart-neats copied to clipboard

Proposal `obtain` / `getOrCreate` function

Open jonasfj opened this issue 2 years ago • 1 comments

With nullability this would likely be useful. Also sometimes you want to force creation and not get a cached value.

We could make it an extension or a new method on Entry.

extension NeatCacheEntry<T> on Entry<T> {
  // Get or create a value.
  Future<T> obtain(
    Future<T> Function() create, {
    Duration? ttl,
    bool purgeCache = false,
  }) async {
    if (purgeCache) {
      final value = create();
      if (ttl != null) {
        await set(value, ttl);
      } else {
        await set(value);
      }
      return value;
    }
    if (ttl != null) {
      return (await get(create, ttl))!;
    }
    return (await get(create))!;
  }
}

jonasfj avatar Jul 27 '23 09:07 jonasfj

Fair question is if create should be allowed to return null.

jonasfj avatar Jul 27 '23 09:07 jonasfj