Skip to content

Query Observer ​

A QueryObserver<TData, TError> coordinates fetching, caching, deduplication, and refetching for a single query.


Creating an Observer ​

dart
final observer = QueryObserver<Post, Exception>(
  cache: cache,
  queryKey: QueryKey(['posts', postId]),
  queryFn: () => api.getPost(postId),
  enabled: true,
  staleDuration: Duration(seconds: 30),
  cacheDuration: Duration(minutes: 5),
  refetchInterval: Duration(minutes: 2), // Periodic background refetch
  refetchOnMount: RefetchOnMount.stale,
  retryCount: 3,
  retryDelay: Duration(seconds: 1),
);

Observer State: query ​

You can inspect the observer's current query state via observer.query:

dart
final query = observer.query;

print('Status: ${query.status}');         // QueryStatus.loading, success, or error
print('isLoading: ${query.isLoading}');   // true on first load with no cached data
print('isFetching: ${query.isFetching}'); // true whenever an async fetch is in flight
print('isSuccess: ${query.isSuccess}');   // true when data is available
print('isError: ${query.isError}');       // true when fetch failed
print('data: ${query.data}');             // TData?
print('error: ${query.error}');           // TError?
print('dataUpdatedAt: ${query.dataUpdatedAt}');

Subscribing to Changes ​

QueryObserver mixes in Observable, enabling listeners to react to query updates:

dart
// Subscribe with a unique integer ID
observer.subscribe(hashCode, () {
  print('State updated: ${observer.query.data}');
});

// Trigger the initial fetch based on refetchOnMount policy
observer.initialize();

// Unsubscribe when no longer listening
observer.unsubscribe(hashCode);

// Or dispose completely
observer.dispose();

Updating Configuration (updateOptions) ​

When parameters change (such as when a widget rebuilds or an enabled flag toggles), update the observer dynamically using updateOptions:

dart
observer.updateOptions(
  QueryOptions(
    queryKey: observer.queryKey,
    queryFn: observer.queryFn,
    enabled: isOnline, // toggling to false cancels active fetches
    refetchInterval: isPolling ? Duration(seconds: 5) : null,
  ),
);
  • When enabled transitions from false to true, the query automatically initializes.
  • When enabled transitions from true to false, in-flight fetches and scheduled interval timers are cleanly cancelled.

Released under the MIT License.