RxJs Observable.empty()。delayWhen()不延迟

时间:2018-04-01 18:05:26

标签: javascript rxjs observable

如果发生错误以允许用户决定继续,我想暂停一个observable。发生错误时,将跳过值。在这里,我只询问用户每三个错误。

Observable.empty().delayWhen(...)的行为与Observable.empty()相似,但Observable.empty().delay()按预期工作,Observable.of(null).delayWhen(...)也是如此。

Subject = Rx.Subject
Observable = Rx.Observable

let i = 0
let subject = new Subject()
  
onFailure = () => {
	// simulate prompting user to continue
  setTimeout(() => {
    subject.next(null)
  }, 3000)
}
          
Observable.from([1,2,3,4,5,6,7,8,9])
      .concatMap(num => {
        return Observable.fromPromise(new Promise((resolve, reject) => {
        	num == 8 ? resolve(num):reject()
        }))
          .catch(err => {
            console.log('rejected '+num)
            i = i % 3; i++;

            if (i < 3) return Observable.empty().delay(500)  // this works
            
            // I don't want to return null but Observable.empty() wont work with delayWhen...
            return Observable.of(null).delayWhen(() => {
              console.log('prompting user...')
              return Observable.create(observer => {
                onFailure()
                subject.take(1).subscribe(() => {
                  console.log('continued after waiting...')
                  observer.next(Observable.empty())
                })
              })
            })

          })
      })
      .subscribe(num => {
        console.log('got '+num)
      })
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.8/Rx.js"></script>

预期:

 rejected 1
 rejected 2
 rejected 3
 prompting user...
 continued after waiting...
 rejected 4
 rejected 5
 rejected 6
 prompting user...
 continued after waiting...
 rejected 7
 got 8
 rejected 9

(不应出现got null值)

注意:

我尝试retryWhen()后跟retry(someNumber),但问题是我需要永远重试,所以我不认为它是正确的运算符。

1 个答案:

答案 0 :(得分:0)

好的,所以我实际上通过实现retry()永远地解决了它...

.retryWhen(errObs => {
    return errObs.mergeMap(err => {
      i = i % 3; i++;

      if (i < 3) return Observable.throw(err)

      return Observable.create(observer => {
        console.log('prompting user...')
        onFailure()
        this.subject.take(1).subscribe(() => {
          console.log('continued after waiting...')
          observer.next(Observable.empty())
        })
      })
    })

  })
  .retry()

但它仍然是来自Observable.empty().delayWhen(...)

的奇怪行为