1
1
import 'dart:async' ;
2
2
import 'dart:convert' ;
3
+ import 'dart:developer' ;
3
4
4
5
import 'package:collection/collection.dart' ;
5
6
import 'package:hive/hive.dart' ;
@@ -11,24 +12,27 @@ class RequestCacheService<T> {
11
12
final Duration cacheDuration;
12
13
final String networkCacheKey;
13
14
final http.Client httpClient;
15
+ final bool checkForUpdates;
16
+ final Box cacheBox;
14
17
15
18
RequestCacheService ({
16
19
required this .fromJson,
17
20
required this .toJson,
21
+ required this .cacheBox,
18
22
this .cacheDuration = const Duration (minutes: 1 ),
19
23
this .networkCacheKey = 'network_cache' ,
20
24
http.Client ? httpClient,
25
+ this .checkForUpdates = false ,
21
26
}) : httpClient = httpClient ?? http.Client ();
22
27
23
28
/// Fetches data from the cache and API.
24
29
Stream <T > fetchData (String url) async * {
25
- final box = await Hive .openBox (networkCacheKey);
26
- final cacheKey = _generateCacheKey (url);
30
+ final cacheKey = url;
27
31
bool cacheEmitted = false ;
28
32
29
33
try {
30
34
// Check for cached data
31
- final cachedEntry = await box .get (cacheKey);
35
+ final cachedEntry = await cacheBox .get (cacheKey);
32
36
if (cachedEntry != null && cachedEntry is Map ) {
33
37
final cachedMap = Map <String , dynamic >.from (cachedEntry);
34
38
final cachedTimestamp =
@@ -42,9 +46,10 @@ class RequestCacheService<T> {
42
46
43
47
final now = DateTime .now ();
44
48
// Decide whether to fetch new data based on cache validity
45
- if (now.difference (cachedTimestamp) < cacheDuration) {
49
+ if (now.difference (cachedTimestamp) < cacheDuration &&
50
+ ! checkForUpdates) {
46
51
// 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 ;
48
53
}
49
54
}
50
55
@@ -73,7 +78,7 @@ class RequestCacheService<T> {
73
78
'data' : toJson (data),
74
79
'timestamp' : DateTime .now ().toIso8601String (),
75
80
};
76
- await box .put (cacheKey, cacheEntry);
81
+ await cacheBox .put (cacheKey, cacheEntry);
77
82
78
83
if (isDataUpdated) {
79
84
yield data;
@@ -90,13 +95,13 @@ class RequestCacheService<T> {
90
95
}
91
96
// Else, we have already emitted cached data, so we can silently fail or log the error
92
97
}
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 ' );
95
105
}
96
106
}
97
-
98
- /// Generates a cache key by hashing the URL.
99
- String _generateCacheKey (String url) {
100
- return url.hashCode.toString ();
101
- }
102
107
}
0 commit comments