rx-polling
rx-polling is a tiny (1KB gzipped) RxJSv6-based library to run polling requests on intervals, with support for:
- pause and resume if the browser tab is inactive/active
- N retry attempts if the request errors
- Different backoff strategies if the request errors:
- exponential: it will wait 2, 4, ... 64, 256 seconds between attempts. (Default)
- random: it will wait a random time amount between attempts.
- consecutive: it will wait a constant time amount between attempts.
- Observables: it accepts any Observable as input and it returns an Observable, which means it can be combined with other Observables as any other RxJS stream.
- If you need to support rxjs of version <= 5.4 you must install v0.2.3 of rx-polling.
Demo
A demo of the library is available at jiayihu.github.io/rx-polling/demo.
Installation
npm install rx-polling --save
Usage
Fetch data from the endpoint every 5 seconds.
import { map } from 'rxjs/operators';
import { ajax } from 'rxjs/ajax';
import polling from 'rx-polling';
const request$ = ajax({
url: 'https://jsonplaceholder.typicode.com/comments/',
crossDomain: true
}).pipe(
map(response => response.response || []),
map(response => response.slice(0, 10))
);
polling(request$, { interval: 5000 })
.subscribe((comments) => {
console.log(comments);
}, (error) => {
console.error(error);
});
Stop polling
Since rx-polling
returns an Observable, you can just .unsubscribe
from it to close the polling.
const request$ = ajax({
url: 'https://jsonplaceholder.typicode.com/comments/',
crossDomain: true
}).pipe(
map(response => response.response || []),
map(response => response.slice(0, 10))
);
let subscription = polling(request$, { interval: 5000 })
.subscribe((comments) => {
console.log(comments);
});
window.setTimeout(() => {
subscription.unsubscribe();
}, 5000);
Combining the polling
You can use the returned Observable
as with any other stream. The sky is the only limit.
const request$ = this.http.get('https://jsonplaceholder.typicode.com/comments/');
let subscription = polling(request$, { interval: 5000 })
.pipe(
filter(comments => comments.filter(comment => comment.isCool))
)
.subscribe((comments) => {
console.log(comments);
});
API
polling(request$, options): Observable
import polling from 'rx-polling';
...
const request$ = this.http.get('someResource').pipe(take(1));
const options = { interval: 5000 };
polling(request$, options)
.subscribe((data) => {
console.log(data);
}, (error) => {
console.error(error);
});
Returns an Observable
which:
- emits each value emitted by
request$
Observable, resubscribed every interval
milli-seconds - errors if
request$
throws AND if after N attempts it still fails. If any of the attempts succeeds then the polling is recovered and no error is thrown - completes Never. Be sure to
.unsubscribe()
the Observable when you're not anymore interested in the polling.
Options and backoff strategies
rx-polling
supports 3 different strategies for delayed attempts on source$ error.
export interface IOptions {
interval: number;
attempts?: number;
backoffStrategy?: 'exponential' | 'random' | 'consecutive';
exponentialUnit?: number;
randomRange?: [number, number];
constantTime?: number;
backgroundPolling?: boolean;
}
const defaultOptions: IOptions = {
attempts: 9,
backoffStrategy: 'exponential',
exponentialUnit: 1000,
randomRange: [1000, 10000],
backgroundPolling: false
};
Browser support
rx-polling supports IE10+, it internally uses document.hidden and
visibilitychange Event.
You might need to polyfill them on older browsers.
Contributing
Contributions are welcome. New commits/Pull Requests must:
-
Have no linter issues. Run lint
script before committing/pushing.
-
Have tests passing. Run test
script before committing/pushing.
@NOTE: testing RxJS is currently really hard. This repo uses Jest contains some custom utilities to improve testing and error reports. The following console output is not standard and totally custom, so be aware of possible issues.
Nevertheless marbles are awesome! You can read more about it in Testing Observables in RxJS6