RXJS Repeat query until a condition is met?

You can use the expand operator for a simple "conditional repeat" behavior.

Just for the example, instead of a result set I changed the query to return a number. The following keep querying until the retrieved number is less than 100

const { defer, empty } = rxjs;
const { expand, toArray} = rxjs.operators;

const query$ = defer(async () =>  Math.floor(Math.random()*1000));
   
query$
  .pipe(
    expand(result => result < 100 ? empty() : query$),
    toArray()
  )
  .subscribe(console.log);
<script src="https://unpkg.com/rxjs/bundles/rxjs.umd.min.js"></script>


You can also use RXJS Interval with TakeWhile operator. Here is the sample code

In Component:

return Observable
  .interval(250)
  .flatMap(() => this.getQueryData())
  .takeWhile(data => this.checklimit(data))
  .subscribe(result => console.log(result);

getQueryData(){
   // HTTTP API call 
}

checklimit(){
  // return true/false
}

We can also use the repeatWhen operator (which is similar to retryWhen but works on complete instead of on error):

this.queryData().pipe(
    repeatWhen(obs => obs),
    filter(data => this.checkLimit()),
    take(1)
).subscribe(result => console.log(result));

Note: the take(1) is needed to stop the repeatWhen loop.

If we need a delay between retries, we can do:

repeatWhen(obs => obs.pipe(delay(1000)))

Tags:

Angular

Rxjs