11import 'dart:async' ;
22import 'dart:convert' ;
3+ import 'dart:developer' ;
34
45import 'package:collection/collection.dart' ;
56import 'package:hive/hive.dart' ;
@@ -11,24 +12,27 @@ class RequestCacheService<T> {
1112 final Duration cacheDuration;
1213 final String networkCacheKey;
1314 final http.Client httpClient;
15+ final bool checkForUpdates;
16+ final Box cacheBox;
1417
1518 RequestCacheService ({
1619 required this .fromJson,
1720 required this .toJson,
21+ required this .cacheBox,
1822 this .cacheDuration = const Duration (minutes: 1 ),
1923 this .networkCacheKey = 'network_cache' ,
2024 http.Client ? httpClient,
25+ this .checkForUpdates = false ,
2126 }) : httpClient = httpClient ?? http.Client ();
2227
2328 /// Fetches data from the cache and API.
2429 Stream <T > fetchData (String url) async * {
25- final box = await Hive .openBox (networkCacheKey);
26- final cacheKey = _generateCacheKey (url);
30+ final cacheKey = url;
2731 bool cacheEmitted = false ;
2832
2933 try {
3034 // Check for cached data
31- final cachedEntry = await box .get (cacheKey);
35+ final cachedEntry = await cacheBox .get (cacheKey);
3236 if (cachedEntry != null && cachedEntry is Map ) {
3337 final cachedMap = Map <String , dynamic >.from (cachedEntry);
3438 final cachedTimestamp =
@@ -42,9 +46,10 @@ class RequestCacheService<T> {
4246
4347 final now = DateTime .now ();
4448 // Decide whether to fetch new data based on cache validity
45- if (now.difference (cachedTimestamp) < cacheDuration) {
49+ if (now.difference (cachedTimestamp) < cacheDuration &&
50+ ! checkForUpdates) {
4651 // Cache is still valid, but we'll fetch new data to check for updates
47- // return; // Uncomment this line to skip fetching new data
52+ return ;
4853 }
4954 }
5055
@@ -73,7 +78,7 @@ class RequestCacheService<T> {
7378 'data' : toJson (data),
7479 'timestamp' : DateTime .now ().toIso8601String (),
7580 };
76- await box .put (cacheKey, cacheEntry);
81+ await cacheBox .put (cacheKey, cacheEntry);
7782
7883 if (isDataUpdated) {
7984 yield data;
@@ -90,13 +95,13 @@ class RequestCacheService<T> {
9095 }
9196 // Else, we have already emitted cached data, so we can silently fail or log the error
9297 }
93- } finally {
94- await box.close ();
98+ } catch (e) {
99+ if (! cacheEmitted) {
100+ // No cached data was emitted before, so we need to throw an error
101+ throw Exception ('Error fetching data from $url : $e ' );
102+ }
103+ // Else, we have already emitted cached data, so we can silently fail or log the error
104+ log ('Error fetching data from $url : $e ' );
95105 }
96106 }
97-
98- /// Generates a cache key by hashing the URL.
99- String _generateCacheKey (String url) {
100- return url.hashCode.toString ();
101- }
102107}
0 commit comments