Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal obtain / getOrCreate function #214

Open
jonasfj opened this issue Jul 27, 2023 · 1 comment
Open

Proposal obtain / getOrCreate function #214

jonasfj opened this issue Jul 27, 2023 · 1 comment
Labels
enhancement New feature or request pkg:neat_cache

Comments

@jonasfj
Copy link
Member

jonasfj commented Jul 27, 2023

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
Copy link
Member Author

jonasfj commented Jul 27, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request pkg:neat_cache
Projects
None yet
Development

No branches or pull requests

1 participant