Skip to content Skip to sidebar Skip to footer

Rxjs: Recursive Http Calls Based On Condition

I retrieve a list using the following command by giving a fixed number of record. In the folowing example, it returns 100 records (I pass the pageIndex value and it should be incre

Solution 1:

A Possible Answer :

You probably want expand and reduce:

I'm assuming page index starts at 0, the page index that you start with before 'expand' must be 1 less than the first page index from your service.

of({
  isComplete: false,
  pageIndex: -1,
  items: []
}).pipe(
  expand(data =>this.employeeService.list(data.pageIndex+1, 100).pipe(
    map(newData => ({...newData, pageIndex: data.pageIndex+1}))
  )),
  takeWhile(data => !(data.isComplete === true), true),
  map(data => data.items),
  reduce((acc, items) => ([...acc, ...items]))
).subscribe(res => {
  this.employees = res;
});

A quick aside about promises:

observableStream.toPromise().then(LAMBDA);

is roughly equivalent to

observableStream.pipe(last()).subscribe(LAMBDA);

last waits for the source to compete and only emits the final value. This drops all other values in the stream.

many people who first work with Observables and Promises tend to assume it works more like:

observableStream.pipe(first()).subscribe(LAMBDA);

so that it takes the first value, then resolves the Promise with that value ASAP. This is, in fact, not the case.


In general, it is wise to stick with one or the other. Observable are a super-set of Promises. Short of third-party libraries expecting promises, there should never be a need to convert an Observable to Promise.

Solution 2:

expand operator is what you're looking for. Example:

this.employeeService.list(100).pipe(
    expand((data) => {
        if(data.isComplete) {
            return of(EMPTY);
        } else {
            returnthis.employeeService.list(100);
        }
    })
).subscribe((data) => {
    //your logic here
});

Post a Comment for "Rxjs: Recursive Http Calls Based On Condition"