rxjs created observable timeout always errors

主宰稳场 提交于 2019-12-23 17:33:32

问题


ok, so now I'm really puzzled. Executing the following code

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')
  )

Prints

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

I don't understand this at all, why does the created Observable error even though it emits a value but the ofd Observable does not??

Using RxJS 5, problem occurs with 5.0.3 in jsbin.com and 5.4.3 in my app.

(Note: This happens with subjects too, which led me to create this example)


回答1:


Observable.of is completing the stream right after the value has been emitted.

Observable.create keeps the observable opened. And that's why the timeout is throwing an error.

Replace

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

By

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

and there's no error anymore.



来源:https://stackoverflow.com/questions/46850852/rxjs-created-observable-timeout-always-errors

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!