RxJs: poll until interval done or correct data received

前端 未结 5 1925
时光取名叫无心
时光取名叫无心 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:29

    A small optimization to the excellent answer from @matt-burnell. You can replace the filter and take operators with the first operator as follows

    Rx.Observable
      .fromPromise(submitJobToQueue(jobData))
      .flatMap(jobQueueData =>
        Rx.Observable.interval(1000)
          .flatMap(() => pollQueueForResult(jobQueueData.jobId))
          .first(x => x.completed)
          .map(() => 'Completed')
          .timeout(60000, Rx.Observable.throw(new Error('Timeout')))
    
      )
      .subscribe(
        x => console.log('Result', x),
        x => console.log('Error', x)
      );
    

    Also, for people that may not know, the flatMap operator is an alias for mergeMap in RxJS 5.0.

提交回复
热议问题