subscribe method
Registers listener and returns the function that removes it again.
The listener is called with each new QueryResult from then on —
including the ones a fetch started by this subscribe produces — but not
with the result that was current before; read that from
currentResult. A listener that throws has its error reported to the
current zone; the other listeners still run. The first listener
attaches the observer to its query, fetches if the options say
a fetch is due (no data yet, or stale data and refetchOnMount), and
arms the stale and polling timers. Removing the last listener detaches
the observer again, as destroy does.
Each returned function removes its own registration, and only once: calling it again does nothing, even if the same listener was added twice.
The first subscribe runs user code — an Enabled.when, a
StaleTime.dynamic, a RefetchOn.when, a RefetchInterval.dynamic, a
PlaceholderData.compute — and a throw there propagates to the caller.
It leaves nothing behind: the listener is removed and the observer
detached again before the error leaves, as if the subscribe had never
happened. (TanStack Query keeps the listener registered in that case.)
Implementation
void Function() subscribe(QueryObserverListener<TData> listener) {
final remove = _listeners.add(listener, onRemoved: _onUnsubscribe);
try {
_onSubscribe();
} catch (_) {
// The handle is the rollback: for a last listener it runs `destroy`,
// which detaches from the query and clears any timer already armed.
remove();
rethrow;
}
return remove;
}