ObservableQuery

API reference


An ObservableQuery is created by calling the client.watchQuery method. It represents a query that can be observed for changes, allowing you to reactively update your UI.

Key Behaviors

RxJS Integration

ObservableQuery implements the RxJS InteropObservable interface which means you can convert it into an RxJS Observable via from(observableQuery). It also provides the subscribe and pipe functions like an RxJS Observable. Refer to the RxJS documentation for additional context and API options.

To get a single result from an ObservableQuery as a Promise, use the firstValueFrom helper:

TypeScript
1import { firstValueFrom, from } from "rxjs";
2
3// The `from` is necessary to turn `observableQuery` into an RxJS observable
4const result = await firstValueFrom(from(observableQuery));

Subscription Lifecycle

  • ObservableQuery instances are only registered with ApolloClient while they have active subscribers

  • Unsubscribing from an ObservableQuery while a request is in flight does not terminate the request

  • Unsubscribing before any value has been emitted removes the query from the tracked list and makes it ineligible for query deduplication

Error Handling

  • ObservableQuery does not terminate on errors - instead it emits a next value with an error property. This ensures ObservableQuery subscriptions can continue receiving updates after errors without resubscription.

Loading States

  • When notifyOnNetworkStatusChange is true (the default), an initial loading state is emitted when subscribing

  • ObservableQuery preserves data when emitting a loading state unless query or variables changed (note: @export variables are not considered for this check)

  • When the query can be fulfilled by the cache or when the link chain responds synchronously, a loading state is omitted

  • cache-only queries initialize with networkStatus: NetworkStatus.ready when there is no data in the cache

  • standby queries initialize with networkStatus: NetworkStatus.ready before subscribing to the query

Promise-returning Methods and retention

  • refetch() and reobserve() return a ResultPromise with an additional .retain() method

  • By default, the network operation is cancelled when ObservableQuery no longer requires the result, such as when ObservableQuery is unsubscribed or variables change, and the returned Promise will reject with an AbortError

  • Calling .retain() keeps the network operation running even when the ObservableQuery no longer requires the result

  • setVariables() and refetch() guarantee that a value will be emitted from the observable, even when the result is deeply equal to the previous result

Active vs Inactive Queries

  • Active queries: Have at least one subscriber and are not skipped or have a fetchPolicy of standby

  • Inactive queries: Have a subscriber but are either skipped or have a fetchPolicy of standby

  • ObservableQuerys without subscribers but with an active network request are handled as if they had a subscriber for the duration of the query

  • Only queries with subscribers can be refetched using ApolloClient.refetchQueries

ObservableQuery functions

Signature

TypeScript
1getCurrentResult(): ObservableQuery.Result<MaybeMasked<TData>>

Used to stitch together functional operators into a chain.

Example

TypeScript
1 import { filter, map } from 'rxjs';
2 
3 observableQuery
4   .pipe(
5     filter(...),
6     map(...),
7   )
8   .subscribe(x => console.log(x));

Signature

TypeScript
1pipe(
2  operators: OperatorFunctionChain<ObservableQuery.Result<TData>, OperatorResult>
3): Observable<OperatorResult>

Subscribes to the ObservableQuery.

Signature

TypeScript
1subscribe(
2  observerOrNext: Partial<Observer<ObservableQuery.Result<MaybeMasked<TData>>>> | ((value: ObservableQuery.Result<MaybeMasked<TData>>) => void)
3): Subscription

Parameters

Name / Type
Description
observerOrNext
Partial<Observer<ObservableQuery.Result<MaybeMasked<TData>>>> | ((value: ObservableQuery.Result<MaybeMasked<TData>>) => void)

Either an RxJS Observer with some or all callback methods, or the next handler that is called for each value emitted from the subscribed Observable.

Update the variables of this observable query, and fetch the new results. This method should be preferred over setVariables in most use cases.

Returns a ResultPromise with an additional .retain() method. Calling .retain() keeps the network operation running even if the ObservableQuery no longer requires the result.

Note: refetch() guarantees that a value will be emitted from the observable, even if the result is deep equal to the previous value.

Signature

TypeScript
1refetch(
2  variables?: Partial<TVariables>
3): ObservableQuery.ResultPromise<ApolloClient.QueryResult<TData>>

Parameters

Name / Type
Description
variables (optional)
Partial<TVariables>

The new set of variables. If there are missing variables, the previous values of those variables will be used.

A function that helps you fetch the next set of results for a paginated list field.

Signature

TypeScript
1fetchMore<TFetchData, TFetchVars>(
2  options: ObservableQuery.FetchMoreOptions<TData, TVariables, TFetchData, TFetchVars>
3): Promise<ApolloClient.QueryResult<TFetchData>>

A function that enables you to execute a subscription, usually to subscribe to specific fields that were included in the query.

This function returns another function that you can call to terminate the subscription.

Signature

TypeScript
1subscribeToMore<TSubscriptionData, TSubscriptionVariables>(
2  options: ObservableQuery.SubscribeToMoreOptions<TData, TSubscriptionVariables, TSubscriptionData, TVariables>
3): () => void

Tears down the ObservableQuery and stops all active operations by sending a complete notification.

Signature

TypeScript
1stop(): void

Update the variables of this observable query, and fetch the new results if they've changed. Most users should prefer refetch instead of setVariables in order to to be properly notified of results even when they come from the cache.

Note: setVariables() guarantees that a value will be emitted from the observable, even if the result is deeply equal to the previous value.

Note: the promise will resolve with the last emitted result when either the variables match the current variables or there are no subscribers to the query.

Signature

TypeScript
1setVariables(
2  variables: TVariables
3): Promise<ApolloClient.QueryResult<TData>>

Parameters

Name / Type
Description
variables
TVariables

The new set of variables. If there are missing variables, the previous values of those variables will be used.

A function that enables you to update the query's cached result without executing a followup GraphQL operation.

See using updateQuery and updateFragment for additional information.

Signature

TypeScript
1updateQuery(
2  mapFn: UpdateQueryMapFn<TData, TVariables>
3): void

A function that instructs the query to begin re-executing at a specified interval (in milliseconds).

Signature

TypeScript
1startPolling(
2  pollInterval: number
3): void

A function that instructs the query to stop polling after a previous call to startPolling.

Signature

TypeScript
1stopPolling(): void

Reevaluate the query, optionally against new options. New options will be merged with the current options when given.

Note: variables can be reset back to their defaults (typically empty) by calling reobserve with variables: undefined.

Signature

TypeScript
1reobserve(
2  newOptions?: Partial<ObservableQuery.Options<TData, TVariables>>
3): ObservableQuery.ResultPromise<ApolloClient.QueryResult<MaybeMasked<TData>>>

Types

The current status of a query’s execution in our system.

Enumeration Members

No request is in flight for this query, but one or more errors were detected.

Indicates that fetchMore was called on this query and that the query created is currently in flight.

The query has never been run before and the query is now currently running. A query will still have this network status even if a partial data result was returned from the cache, but a query was dispatched anyway.

Indicates that a polling query is currently in flight. So for example if you are polling a query every 10 seconds then the network status will switch to poll every 10 seconds whenever a poll request has been sent but not resolved.

No request is in flight for this query, and no errors happened. Everything is OK.

Similar to the setVariables network status. It means that refetch was called on a query and the refetch request is currently in flight.

If setVariables was called and a query was fired because of that then the network status will be setVariables until the result of that query comes back.

Indicates that a @defer query has received at least the first chunk of the result but the full result has not yet been fully streamed to the client.

Properties
Name / Type
Description
Operation data
DataValue.Complete<TData> | DataValue.Streaming<TData> | DataValue.Partial<TData> | undefined

An object containing the result of your GraphQL query after it completes.

This value might be undefined if a query results in one or more errors (depending on the query's errorPolicy).

"complete" | "streaming" | "partial" | "empty"

Describes the completeness of data.

  • empty: No data could be fulfilled from the cache or the result is incomplete. data is undefined.

  • partial: Some data could be fulfilled from the cache but data is incomplete. This is only possible when returnPartialData is true.

  • streaming: data is incomplete as a result of a deferred query and the result is still streaming in.

  • complete: data is a fully satisfied query result fulfilled either from the cache or network.

A single ErrorLike object describing the error that occured during the latest query execution.

For more information, see Handling operation errors.

boolean

⚠️ Deprecated

This field will be removed in a future version of Apollo Client.

Describes whether data is a complete or partial result. This flag is only set when returnPartialData is true in query options.

Network info
boolean

If true, the query is still in flight and results have not yet been returned.

NetworkStatus

A number indicating the current network state of the query's associated request. See possible values.

Used in conjunction with the notifyOnNetworkStatusChange option.

Feedback

Edit on GitHub

Ask Community