angular2 observable interval - Deal with out-of-order responses

317 views Asked by At

I have a scenario where I need to call a service method(which will call HTTP post method) repetitively until I get the results and for that I am using interval. In below code the getReportResultsList(id) method will be get called in the interval of 100 ms.

The problem is, the server may take 300 ms time to process the first request and return the results. But at the same time 2 more requests are going to the server to get the results because of interval(100). So after getting the results from the first request i don't want to process the unexpected 2nd and 3rd requests response results.

So I don't want to process the 2nd and 3rd responses. Can any one know how to to deal with these out of order responses?

Thanks.

let subscriber = Observable.interval(100).subscribe(() => {
                   this.reportService.getReportResultList(id)
                   .subscribe(result => {
                     this.reportResults = result;
                     if (this.reportResults) {
                       this.prepareViewData(result);
                       subscriber.unsubscribe();
                     }
                   });
                 });
1

There are 1 answers

1
David M. On

As the commenters mentioned above, you don't need to call the server 10 times per second for your use case. You only need to call the server until you actually have a result.

More appropriate to use the retryWhen semantics of Observables.

Something along these lines:

this.reportService.getReportResultList(id)
       .subscribe(result => {
         this.reportResults = result;
         if (!this.reportResults) {
           throw 'empty'; 
         }
         this.prepareViewData(result);
       })
       .retryWhen((errors) => return errors.delay(10));

You need to be a little more thorough in the retryWhen handler because other errors could be raised (example: an HTTP 50x error) but that'll give you an idea.