Search code examples
angularrxjsreactive-programming

Angular RxJs: Poll HTTP request until timeout or positive response from server


I am new to RxJs. I need to poll a http request and continue polling until I get a positive response or a specified amount of time has elapsed (don't want to poll forever).

I am using Angular 8 and Typescript. Here is my code:

this.httpClient.get('http://localhost:8060/api/portal/v1/payment/fetch/' + shopId + '/0/10').pipe(
          repeatWhen(obs => obs.pipe(delay(5000))),
          filter((data: ResponseModel<any>) => {
            console.log('Data:' + data);
            return data.status === 'success';
          }),
          take(1)
        ).subscribe(result => {
          console.log('Result: ' + result);
        });

The code above works for positive response from server but if there is no positive response it polls forever which is not the desired effect. How do I add a timeout in the above functionality?


Solution

  • Based on the suggestion in the first comment, I tweaked a few things and ended up with the following that works

    // Create an Observable that emits every 5 seconds
    interval(5000).pipe(
    
              // Since the httpClient returns an Observable, wrap it with a switchMap
              switchMap(() => this.httpClient.get('http://localhost:8060/api/portal/v1/payment/fetch/' + shopId + '/0/10')),
    
              // Filter only the successful http responses
              filter((data: ResponseModel<any>) => {
                console.log('Data:' + JSON.stringify(data));
                return data.status === 'success';
              }),
    
              // Emit only the first value emitted by the source
              take(1),
    
              // Time out after 30 seconds
              timeout(30000),
            ).subscribe((result: ResponseModel<any>) => {
    
              console.log('Result: ' + JSON.stringify(result));
    
            }, error => {
              console.log('Error: ' + error);
            });