The poll operator is a custom RxJS operator that simplifies the process of polling APIs to keep data up-to-date. It allows developers to create observables that periodically emit data at specified intervals, abstracting away the complexity of managing polling intervals and API requests. This operator is especially useful when real-time updates are required but the server does not support push notifications (WebSockets, Server-Sent Events, etc.). It seamlessly integrates with other RxJS operators, enabling developers to build reactive pipelines for handling data streams.
Examples
Example 1: Basic Polling
Poll data at a specified interval. The polling function supports Promise, Observable, or primitive values:
You can add takeUntil, takeWhile, or other RxJS operators to control when polling ends.
Example 3: Poll with initialValue
By default, the poll initial result is {status: 'loading', isLoading: true, error: null, data: null}, which is convenient for displaying a loading spinner. However, in some cases, you may not want to display a loading spinner. You can set initialValue to any value you want:
Use the forceRefresh observable or signal to trigger the execution of pollingFn whenever necessary, such as in response to user actions. The emitted value from forceRefresh will be passed as the input to paramsBuilder (if provided) or directly to pollingFn.
Example 6: Advanced Example - Datagrid with Polling
The datagrid below will automatically refresh every 10 seconds. Additionally, whenever there's a change in the input, triggering filtering, sorting, or pagination, the API will be promptly called, accompanied by a spinner indicating loading.
pollingFn: (input?: Input) => Observable<Data> | Promise<Data> | Data
Required. A function that returns an Observable, Promise, or primitive value. The function receives parameters built from forceRefresh or paramsBuilder.
interval: number
Required. The interval in milliseconds between each poll.
forceRefresh?: Observable<Input> | Signal<Input>
(Optional) An Observable or Signal that triggers a manual refresh. The emitted value is passed to paramsBuilder (if provided) or directly to pollingFn.
paramsBuilder?: (input: Input) => any
(Optional) A function that builds parameters for the polling function based on the forceRefresh value. Useful when the forceRefresh value does not match the structure of pollingFn parameters.
initialValue?: AsyncState<Data>
(Optional) An initial AsyncState value. Defaults to { status: 'loading', isLoading: true, error: null, data: null }.
delay?: number
(Optional) Delay in milliseconds before starting the first poll. Defaults to 0 (starts immediately).
Returns
An observable that emits AsyncState<Data> objects with status, isLoading, error, and data properties.