Here is the implementation for a function that takes a Promise-based fetch function and a function that decides if a response has been successful (from a polling perspective) and polls the fetch function until the isSuccess
function returns true
:
import { Observable, from, interval } from 'rxjs';
import { switchMap, takeWhile } from 'rxjs/operators';const POLLING_INTERVAL = 600; // in millisecondsfunction poll(fetchFn, isSuccessFn, pollInterval = POLLING_INTERVAL) {
return interval(POLLING_INTERVAL).pipe(
switchMap(() => from(fetchFn())),
takeWhile((response) => isSuccessFn(response))
);
}
The above leverages RxJS 5 and uses its new pipe
syntax. If we walk through it:
- create an Observable that emits every 600ms (by default) using
interval
- pipe that into
switchMap
, this operator essentially replaces the Observable’s value to another one, in this instance, replace the emitted interval count with an Observable created from the Promise returned byfetchFn
takeWhile
theisSuccessFn
returns true
To go into a bit more detail about switchMap
, it’s a bit like doing this in a Promise chain:
const promiseChain = Promise
.resolve()
.then(
() =>…