angularrxjsangular2-observables

Chain API http request that depends on response of previous request


I'm trying to implement chain http request that will be repeated X times and stop when there is no response from last request.

How it should work.

For example first I call

http://example.com/?skip=0

and response is:

{
   skip=10
},

than I call

http://example.com/?skip=10
...
http://example.com/?skip=20

and on skip 20 response is

{
  "message" : "You reach the end"
}

I need to stop there. But I have to repeat requests when I'm getting "skip" in response and repeat them on the way that I add skip into next request.

Thanks


Solution

  • Based on the description it sounds like you actually mean to "paginate" the same query rather than chaining several dependent queries. For that you can use expand:

    // Start with skip 
    Observable.of({skip: 0})
      // Feeds the response resulting stream back into this function
      .expand((response) => {
        // Continue expanding if there is a skip parameter
        if (response.skip >= 0)
          return this.http.get(`http://example.com/?skip=${skip}`);
        // Stop expanding if there is no more data
        else
          return Observable.empty();
      }, 1 /* Limit the number of consecutive queries*/);