Angular stop making api request after given milliseconds even if it's not succeeded

Issue

I am trying to fetch status from backend until the condition is met but I don’t want to overload server by making request forever 🙂 .I want to stop making request after one minute.
here is the code

  this.statusService
.getStatus(this.itemId).pipe(
repeatWhen(obs => obs.pipe(delay(500))),
filter(data => {
  if(data.status === 'done'){
    return true;
  }else{
    return false;
  }
   }),
take(1)
).subscribe(result =>{
  console.log(‘done')
});

I tried timeout() but it doesn’t stop making request

  this.statusService
.getStatus(this.itemId).pipe(
 timeout(60000),
repeatWhen(obs => obs.pipe(delay(500))),
filter(data => {
  if(data.status === 'done'){
    return true;
  }else{
    return false;
  }
   }),
take(1)
).subscribe(result =>{
  console.log(‘done')
});

Solution

UPDATED:

One simple solution can be:

const apiCall$ = this.statusService.getStatus(this.itemId)
  .pipe(
    delay(1000),
    repeat(),
    filter(data => (data.status === 'done'))
  );

const timeout$ = of(false).pipe(delay(3000));

// The observable to emit first is used
race([apiCall$, timeout$])
  .pipe(take(1))
  .subscribe(result => {
    console.log(result);
  });

Answered By – munleashed

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published