Search code examples
angulartypescriptrxjspolling

Adding a delay between webservice calls in typescript


I am developing a simple web app that sends a big file to a server for processing. Processing may take a quite of a time that exceeds server timeout that i can't tune, so i decided to design two services - one sends data to a server, another one constantly checks processing result. But it seems like that constant checking takes too much resources and browser starts to slow down. Here's the code:

      try {
        this.processService.processData(this.byteArray); //data sent for a processing

        const processingResult: ProcessResult = new ProcessResult();
        processingResult.traces = []

        do {
          this.processService.getResult().then(result => processingResult.traces = result?.traces);
        } while (processingResult.traces.length === 0);

        this.traces = processingResult.traces;
      } catch (error) {
        console.error(error);
      }
    }
  }

What is the best practice to add some sort of a delay between ws calls in TypeScript? Thanks.


Solution

  • I recommend interval in combination with skipWhile and take.

    // SERVER
    
    let ready = false;
    
    function veryLongServerRequest(): void {
      timer(10000).subscribe(
        () => ready = true,
      );
    }
    
    function isServerReady(): Observable<boolean> {
      return of(ready);
    }
    
    // CLIENT
    
    veryLongServerRequest();
    
    interval(500).pipe(
      tap(i => console.log('Polling try ' + i)),
      switchMap(() => isServerReady()),
      skipWhile(b => !b),
      take(1),
    ).subscribe(() => console.log('FINISHED!'));
    

    See working Stackblitz: https://stackblitz.com/edit/rxjs-fqbwon?file=index.ts

    Edit: You can simplify skipWhile + take to first

    See working Stackblitz: https://stackblitz.com/edit/rxjs-tc2ztd?file=index.ts