Skip to content

Caching & Garbage Collection ​

fquery_core employs a deterministic, reference-counted garbage collection (GC) mechanism to keep memory overhead minimal.


How Garbage Collection Works ​

  1. 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 QueryCache and will never be garbage collected.
  2. Observer Detachment: When an observer is disposed (observer.dispose()), it detaches from QueryCache.
  3. Countdown Begins: If the detached observer was the last active observer for that query, QueryCache starts a timer based on the query's cacheDuration.
  4. Purge: If the timer expires before any new observer subscribes to that key, the query is purged from QueryCache.
  5. 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.

Released under the MIT License.