I need to repeat the query if the field of the returned object has the value 'INPROGRESS' with a delay so as not to clog up the server.
If another field value is returned, the loop stops and I perform some action in subscribe()
with its response.
My attempts so far have ended up with this code, where unfortunately the queries repeat infinitely.
this.service
.query(id: number)
.pipe(
repeatWhen(obs => obs.pipe(delay(1000))),
filter((response) => response.Status === 'INPROGRESS'),
take(1),
)
.subscribe(...)
CodePudding user response:
with a recursie function, something like this should do the job:
private myFunc(){
this.myRecursiveFunc(1).subscribe(response => console.log(response));
}
private myRecursiveFunc(id: number, response?:any):Observable<any>{
if(response && response.Status !== 'INPROGRESS'){
return of(response);
}
return this.service.query(id).pipe(
delay(1000),
concatMap(response => this.myRecursiveFunc(id, response)
);
}
CodePudding user response:
rxjs has expand operator which will allow us to make recurive api call
Try this
this.service
.query(id: number)
.pipe(
delay(1000),
expand((response: any) => {
if (response.Status === 'INPROGRESS') {
return return this.service
.query(id: number).pipe(delay(1000));
}
return EMPTY;
}),
takeLast(1)
)
.subscribe(...)
CodePudding user response:
https://stackblitz.com/edit/rxjs-kafps9?file=index.ts
this.service.query(id: number).pipe(
repeat({ delay: 1000 }),
skipWhile((response) => response.Status === 'INPROGRESS'),
take(1),
).subscribe(...)