Skip to content

Instantly share code, notes, and snippets.

@killerchip
Last active January 1, 2018 06:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save killerchip/5f26dea23ce5bd911402dcdd02242329 to your computer and use it in GitHub Desktop.
Save killerchip/5f26dea23ce5bd911402dcdd02242329 to your computer and use it in GitHub Desktop.
Angular tip: RxJS a source until certain condition

Monitor until condition

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment