Query Cache
The QueryCache is the central nervous system of fquery_core. It stores all cached queries, tracks active observers, manages garbage collection, and applies state transitions via an internal reducer.
dart
final cache = QueryCache(
defaultQueryOptions: DefaultQueryOptions(
enabled: true,
refetchOnMount: RefetchOnMount.stale,
staleDuration: Duration(seconds: 30),
cacheDuration: Duration(minutes: 5),
refetchInterval: null,
retryCount: 3,
retryDelay: Duration(seconds: 1, milliseconds: 500),
),
);Cache Operations
1. Invalidation (invalidateQueries)
Marks matching queries as invalidated/stale.
- Active queries (currently subscribed to by an enabled, non-disposed observer) will refetch immediately.
- Inactive queries will mark
isInvalidated = true, prompting a fresh fetch the next time an observer mounts.
dart
// Prefix matching: invalidates ['todos'], ['todos', 1], ['todos', {'status': 'done'}]
cache.invalidateQueries(['todos']);
// Exact matching: only invalidates ['todos']
cache.invalidateQueries(['todos'], exact: true);2. Removal / Reset (removeQueries)
Alters or purges queries in the cache:
- Active queries: If active observers are subscribed, removing the query initiates a hard reset (similar to TanStack Query): the cached query is reset to its initial loading state (
data: null,error: null,status: QueryStatus.loading) and observers immediately trigger a fresh fetch. - Inactive queries: If no observers are currently subscribed, the query is completely removed from the cache and its active GC timer is cancelled.
dart
// Prefix matching: removes/resets all queries starting with ['todos']
cache.removeQueries(['todos']);
// Exact matching: only removes/resets the exact key
cache.removeQueries(['todos', 42], exact: true);3. Direct Data Manipulation (getQueryData / setQueryData)
Read or mutate query data directly without triggering a network fetch:
dart
// Reading data synchronously
final todos = cache.getQueryData<List<Todo>, Exception>(['todos']);
// Manually updating data (e.g. after a mutation or websocket event)
cache.setQueryData<List<Todo>, Exception>(['todos'], (previous) {
final current = previous ?? <Todo>[];
return [...current, newTodo];
});4. Monitoring Fetch Status (isFetching)
QueryCache exposes an isFetching getter that returns the total count of queries currently in a fetching state:
dart
if (cache.isFetching > 0) {
print('Network activity in progress (${cache.isFetching} queries)');
}