RxJs: poll until interval done or correct data received

前端 未结 5 1993
时光取名叫无心
时光取名叫无心 2021-02-02 09:48

How do i execute the following scenario in the browser with RxJs:

  • submit data to queue for processing
  • get back the job id
  • poll another endpoint e
5条回答
  •  不要未来只要你来
    2021-02-02 10:50

    Angular / typescript rewritten solution from above:

    export interface PollOptions {
      interval: number;
      timeout: number;
    }
    
    const OPTIONS_DEFAULT: PollOptions = {
      interval: 5000,
      timeout: 60000
    };
    
    @Injectable()
    class PollHelper {
      startPoll(
        pollFn: () => Observable, // intermediate polled responses
        stopPollPredicate: (value: T) => boolean, // condition to stop polling
        options: PollOptions = OPTIONS_DEFAULT): Observable {
        return interval(options.interval)
          .pipe(
            exhaustMap(() => pollFn()),
            first(value => stopPollPredicate(value)),
            timeout(options.timeout)
          );
      }
    }
    

    Example:

    pollHelper.startPoll(
      () => httpClient.get(...),
      response => response.isDone()
    ).subscribe(result => {
      console.log(result);
    });
    

提交回复
热议问题