-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic_usage.dart
More file actions
49 lines (38 loc) · 1.95 KB
/
basic_usage.dart
File metadata and controls
49 lines (38 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// ignore_for_file: avoid_print
import 'package:vault_cache/vault_cache.dart';
Future<void> main() async {
// Create a cache with a 5-minute TTL and LRU eviction for up to 100 entries.
final cache = VaultCache<String, String>(
policy: CachePolicy(
ttl: const Duration(minutes: 5),
maxSize: 100,
eviction: LruStrategy<Object?>(),
),
l1: MemoryStore<String, String>(
maxSize: 100,
eviction: LruStrategy<String>(),
),
);
// ── Manual set / get ──────────────────────────────────────────────────────
await cache.set('greeting', 'Hello, vault_cache!');
final greeting = await cache.get('greeting');
print('get: $greeting'); // Hello, vault_cache!
// ── getOrFetch: fetch once, cache forever (within TTL) ───────────────────
var fetchCount = 0;
Future<String> fakeFetch() async {
fetchCount++;
print(' → fetching from remote (call #$fetchCount)');
return 'data from server';
}
final first = await cache.getOrFetch('data', fetcher: fakeFetch);
final second = await cache.getOrFetch('data', fetcher: fakeFetch);
print('first: $first'); // data from server
print('second: $second'); // data from server (served from cache)
print('fetch calls: $fetchCount'); // 1
// ── Invalidation ──────────────────────────────────────────────────────────
await cache.invalidate('greeting');
print('after invalidate: ${await cache.get("greeting")}'); // null
// ── Stats ─────────────────────────────────────────────────────────────────
print('stats: ${cache.stats}');
await cache.dispose();
}