dart-neats
dart-neats copied to clipboard
Proposal `obtain` / `getOrCreate` function
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))!;
}
}
Fair question is if create should be allowed to return null.