Make requests one after another until satisfactory data is found in rxjs

246 Views Asked by At

I have an array of requests. I want to make the first request and check whether the response ({active: true/false}) is true or false. If the response has active: true, do not send other requests and return info. If the response has active: false, send another request and make the same check.

fakeChildService(child: Child): Observable<{active: boolean, info: string}>
{...}


let requests = [];
let children = action['children'];
children.map((child: Child) => {
   requests.push(this.myService.fakeChildService(child));
})
2

There are 2 best solutions below

0
Abdullah Qudeer On

You can use the repeatWhen operator along with other operators to conditionally repeat the request based on the response data. For example:

import { from, interval, of } from 'rxjs';
import { concatMap, repeatWhen, takeUntil, filter } from 'rxjs/operators';

 

fakeChildService(child: Child): Observable<{active: boolean, info: string}>
{...}
 
GetSatisfactoryData(child:any) {

    const interval$ = interval(2000);
    interval$
      .pipe(
        concatMap(() => from(this.fakeChildService(child))),
        filter((data) => data.active),
        takeUntil(interval$.pipe(repeatWhen(() => interval$)))
      ).subscribe((data) => {
        console.log('found:', data.info);
      });
  }
0
arunkumaraqm On

We ended up calling the service recursively for the children one by one and stopping the recursion when the satisfactory data is found.