watchQuery<T> method

Stream<QoraState<T>> watchQuery<T>({
  1. required Object key,
  2. required Future<T> fetcher(),
  3. QoraOptions? options,
  4. CancelToken? cancelToken,
})

Create a reactive Stream of QoraState for a query.

Behaviour

StreamBuilder<QoraState<User>>(
  stream: client.watchQuery<User>(
    key: ['users', userId],
    fetcher: () => api.getUser(userId),
  ),
  builder: (context, snapshot) {
    return switch (snapshot.data) {
      Loading() => const CircularProgressIndicator(),
      Success(:final data) => UserWidget(data),
      Failure(:final error) => ErrorWidget('$error'),
      _ => const SizedBox.shrink(),
    };
  },
)

Implementation

Stream<QoraState<T>> watchQuery<T>({
  required Object key,
  required Future<T> Function() fetcher,
  QoraOptions? options,
  CancelToken? cancelToken,
}) async* {
  _assertNotDisposed();

  final normalized = normalizeKey(key);
  final opts = config.defaultOptions.merge(options);
  final entry = _getOrCreateEntry<T>(normalized);
  _requestGcTime(entry, opts.gcTime);

  // Inject any pending hydration data (from PersistQoraClient or SsrHydrator).
  _applyPendingHydration<T>(normalized);

  // Apply initialData / placeholderData before the subscriber is counted
  // so isFirstFetch reflects the pre-populated state correctly.
  _applyInitialData<T>(entry, opts);

  // Register subscriber: prevents GC while stream is active.
  entry.addSubscriber();
  entry.gcTimer?.cancel();

  // Dependency subscription: cancelled in finally.
  StreamSubscription<QoraState<dynamic>>? depSub;

  // Invalidation listener: cancelled in finally.
  StreamSubscription<void>? invalidationSub;

  // Local polling timer: owned exclusively by this watcher instance.
  //
  // Previously this was stored on `entry.refetchTimer` (shared mutable
  // field). When two callers subscribed to the same key concurrently, the
  // second setup cancelled the first caller's timer and replaced it with its
  // own. When the first caller's stream was cancelled, its finally-block then
  // cancelled the second caller's timer: leaving the second caller without
  // polling for the rest of its lifetime.
  //
  // By keeping the timer local, each watcher independently manages its own
  // polling lifecycle. Duplicate fetches are harmless because _doFetch()
  // deduplicates concurrent requests via _pendingRequests.
  Timer? localRefetchTimer;

  try {
    if (opts.enabled) {
      // Decide whether to fetch on mount.
      final shouldRefetchOnMount =
          opts.refetchOnMount ?? config.refetchOnMount;
      final isFirstFetch = entry.state is Initial<T>;
      final isStale = entry.isStale(opts.staleTime);

      if (opts.dependsOn != null) {
        // Reactive dependent query: wait for the dependency to have data.
        final depNorm = normalizeKey(opts.dependsOn!);
        final depEntry = _getOrCreateEntry<dynamic>(depNorm);

        if (depEntry.state.dataOrNull != null) {
          // Dependency already resolved: proceed with normal fetch logic.
          if (isFirstFetch || (shouldRefetchOnMount && isStale)) {
            // Defer the fetch to the next event-loop iteration so that
            // `yield* entry.stream` below has time to attach its subscriber
            // to `_controller` before `_doFetch` calls
            // `entry.updateState(Loading(...))` / `_controller.add(...)`.
            // Without this deferral the Loading transition is emitted to a
            // broadcast controller that has no listeners yet and is silently
            // dropped, causing the watcher to jump directly from Initial to
            // Success (or to miss the Loading state entirely).
            unawaited(
              Future<void>.delayed(Duration.zero, () {
                if (_isDisposed || !entry.isActive) return;
                unawaited(
                  _backgroundFetch<T>(
                    normalized,
                    entry,
                    fetcher,
                    opts,
                    cancelToken: cancelToken,
                  ),
                );
              }),
            );
          }
        } else {
          // Dependency not yet ready: subscribe and fire when it resolves.
          depSub = depEntry.stream.listen((depState) {
            if (depState.dataOrNull != null &&
                !_isDisposed &&
                entry.isActive) {
              depSub?.cancel();
              depSub = null;
              unawaited(
                _backgroundFetch<T>(normalized, entry, fetcher, opts),
              );
            }
          });
        }
      } else {
        if (isFirstFetch || (shouldRefetchOnMount && isStale)) {
          // Defer the fetch to the next event-loop iteration so that
          // `yield* entry.stream` below has time to attach its subscriber
          // to `_controller` before `_doFetch` calls
          // `entry.updateState(Loading(...))` / `_controller.add(...)`.
          // Without this deferral the Loading transition is emitted to a
          // broadcast controller that has no listeners yet and is silently
          // dropped, causing the watcher to jump directly from Initial to
          // Success (or to miss the Loading state entirely).
          unawaited(
            Future<void>.delayed(Duration.zero, () {
              if (_isDisposed || !entry.isActive) return;
              unawaited(
                _backgroundFetch<T>(
                  normalized,
                  entry,
                  fetcher,
                  opts,
                  cancelToken: cancelToken,
                ),
              );
            }),
          );
        }
      }

      // Refetch when the query is invalidated while this watcher is active
      // ([invalidate], tag/predicate invalidation, refetchOnWindowFocus).
      // The signal is emitted only by an explicit invalidation, never by a
      // fetch, so a fetch that fails immediately cannot re-trigger itself.
      // Concurrent watchers on the same key are deduplicated by _doFetch.
      invalidationSub = entry.invalidations.listen((_) {
        if (_isDisposed || !entry.isActive) return;
        if (cancelToken?.isCancelled == true) return;
        if (opts.dependsOn != null) {
          final depNorm = normalizeKey(opts.dependsOn!);
          if (_cache.get<dynamic>(depNorm)?.state.dataOrNull == null) return;
        }
        unawaited(
          _backgroundFetch<T>(
            normalized,
            entry,
            fetcher,
            opts,
            cancelToken: cancelToken,
          ),
        );
      });

      // Setup polling interval: stored in a local variable, not on the
      // shared entry, to prevent cross-watcher timer cancellation.
      if (opts.refetchInterval != null) {
        localRefetchTimer = Timer.periodic(opts.refetchInterval!, (_) {
          if (!_isDisposed && entry.isActive) {
            unawaited(
              _backgroundFetch<T>(normalized, entry, fetcher, opts),
            );
          }
        });
      }
    }

    // Yield the current state then forward all future updates.
    yield* entry.stream;
  } finally {
    depSub?.cancel();
    invalidationSub?.cancel();
    localRefetchTimer?.cancel();
    entry.removeSubscriber();
    _scheduleGC(normalized);
  }
}