Caching & Garbage Collection
fquery_core employs a deterministic, reference-counted garbage collection (GC) mechanism to keep memory overhead minimal.
How Garbage Collection Works
- Active Observers Prevent Collection: As long as at least one active (non-disposed) observer is subscribed to a query key, that query remains pinned in
QueryCacheand will never be garbage collected. - Observer Detachment: When an observer is disposed (
observer.dispose()), it detaches fromQueryCache. - Countdown Begins: If the detached observer was the last active observer for that query,
QueryCachestarts a timer based on the query'scacheDuration. - Purge: If the timer expires before any new observer subscribes to that key, the query is purged from
QueryCache. - Re-mount Resets Timer: If a new observer subscribes to the key before the timer expires, the timer is cancelled and the cached data is immediately available.
Longest Lifetime Wins
When multiple observers subscribe to the same query key with different cacheDuration values, QueryCache automatically adopts the longest duration:
dart
// Observer 1 requests 2 minutes
final o1 = QueryObserver(
cache: cache,
queryKey: QueryKey(['data']),
queryFn: fetchData,
cacheDuration: Duration(minutes: 2),
);
// Observer 2 requests 10 minutes
final o2 = QueryObserver(
cache: cache,
queryKey: QueryKey(['data']),
queryFn: fetchData,
cacheDuration: Duration(minutes: 10),
);
// If o1 and o2 are disposed, the query will be retained for 10 minutes.