In this scenario we want to repeatedly monitor an API endpoint, until it retuns a specific value (or condition).
Explanation:
- We use
interval
operator to create an observable that emits a dummy event (a counter) on specific intervals. - We use these dummy events to trigger calls to remove API, and merge the result back to the stream, with
mergeMap
. - Finally with
takeWhile
we check if the condition we want is met. If the conidition is met then- the particular event is not emitted
- the transmition stops
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/Observable/interval';
import 'rxjs/add/operators/mergeMap';
import 'rxjs/add/operators/takeWhile';
...
const monitor = Observable.interval(2000) // parameter is milliseconds
.mergeMap (() => this.httpClient.get(remoteURL) ) // call remote API that returns Χ
.takeWhile ((X) => X === desiredValue /* condition that defines if the event will be emitted.
monitor.subscribe((X) => /* handle the events here */ );
...
Note: The above code works for Angular with RxJS 5.4 and older. With RxJS 5.5 .pipe
can used to apply operators.