Skip to content
This repository was archived by the owner on Oct 17, 2024. It is now read-only.

Commit 6d2de25

Browse files
authored
Invalidate async cache on exception (#132)
* Invalidate async cache on exception When the callback throws an exception, the startStaleTime was not called, so the cache was not refreshed. Because of this, future calls to this cache returned with the exception.
1 parent 38ace5f commit 6d2de25

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

lib/src/async_cache.dart

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -60,12 +60,12 @@ class AsyncCache<T> {
6060
if (_cachedStreamSplitter != null) {
6161
throw StateError('Previously used to cache via `fetchStream`');
6262
}
63-
if (_cachedValueFuture == null) {
64-
_cachedValueFuture = callback();
65-
await _cachedValueFuture;
63+
final result = _cachedValueFuture ??= callback();
64+
try {
65+
return await result;
66+
} finally {
6667
_startStaleTimer();
6768
}
68-
return _cachedValueFuture!;
6969
}
7070

7171
/// Returns a cached stream from a previous call to [fetchStream], or runs

test/async_cache_test.dart

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,4 +158,16 @@ void main() {
158158
}));
159159
expect(cache.fetchStream(call).toList(), completion(['1', '2', '3']));
160160
});
161+
162+
test('should invalidate even if the future throws an exception', () async {
163+
cache = AsyncCache.ephemeral();
164+
165+
Future<String> throwingCall() async => throw Exception();
166+
await expectLater(cache.fetch(throwingCall), throwsA(isException));
167+
// To let the timer invalidate the cache
168+
await Future.delayed(Duration(milliseconds: 5));
169+
170+
Future<String> call() async => 'Completed';
171+
expect(await cache.fetch(call), 'Completed', reason: 'Cache invalidates');
172+
});
161173
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy