Search code examples
angularrxjsobservablereactivex

Keep 'monitoring' an API endpoint until I get my value with Angular HttpClient


I have an API endpoint which when queried returns a status update of a set of specific objects that have been processed at the time.

E.g. { objects: 10, processed: 5)

I want with my Angular 5 HttpClient to create an observable that will keep querying this API (e.g. every 1 sec) until I get the result I want (objects: 10, processed: 10).

My idea is to create an observable that will transmit these intermediate "status" updates as events, and when the condition is met to transmit the Complete event.

What is baffles me is are the facts: * that HttpClient is a cold stream * the fact that it completes after a single response from the API.

So I kind have to keep creating new observables (HttpClient) requests and then keep merging them to my own single observable.

Any ideas on how to approach this with RxJS and Angular 5?

Thank you in advance


Solution

  • You can do this:

    Observable.interval(1000)
              .flatMap(() => this.someService.callApi())
              .filter(actualResult => actualResult === expectedResult)
              .takeWhile(actualResult => actualResult === expectedResult)
              .subscribe(() => // handle your data here)
    

    This will start an interval stream for every second, turn it into an observable of the API call results, which will continue until the desired result is found.