rxjs创建了可观察的超时总是错误

时间:2017-10-20 14:05:03

标签: timeout rxjs rxjs5

好的,所以现在我真的很困惑。执行以下代码

const created = Rx.Observable.create(observer => {
  observer.next(42)
})
const ofd = Rx.Observable.of(42)

const createSub = name => [
  val => console.log(`${name} received ${val}`),
  error => console.log(`${name} threw ${error.constructor.name}`)
]

created
  .timeout(100)
  .subscribe(
    ...createSub('created')
  )

ofd
  .timeout(100)
  .subscribe(
    ...createSub('ofd')
  )

打印

"created received 42"
"ofd received 42"
"created threw TimeoutError"

我根本不理解这一点,为什么created Observable错误,即使它发出一个值,但ofd Observable却没有?

使用RxJS 5,jsbin.com中的5.0.3和我的应用中的5.4.3会出现问题。

(注意:这也发生在主题上,这导致我创建了这个例子)

1 个答案:

答案 0 :(得分:2)

Observable.of在发出值后立即完成流。

Observable.create保持可观察性的打开。这就是timeout抛出错误的原因。

替换

const created = Rx.Observable.create(observer => {
  observer.next(42)
})

通过

const created = Rx.Observable.create(observer => {
  observer.next(42);
  observer.complete();
})

并且没有任何错误。