问题描述
当我从头开始创建一个 observable 并且有观察者错误,然后完成时,订阅的完成部分永远不会被调用.
When I create an observable from scratch, and have the observer error, then complete, the done part of the subscription never is invoked.
var observer = Rx.Observable.create(function(observer){
observer.onError(new Error('no!'));
observer.onCompleted();
})
observer.subscribe(
function(x) { console.log('succeeded with ' + x ) },
function(x) { console.log('errored with ' + x ) },
function() { console.log('completed') }
)
输出为:
errored with Error: no!
我希望它是:
errored with Error: no!
completed
如果我更改代码以调用 onNext 而不是 onError,observable 将正确完成:
If I change the code to invoke onNext instead of onError, the observable properly completes:
var observer = Rx.Observable.create(function(observer){
observer.onNext('Hi!');
observer.onCompleted();
})
observer.subscribe(
function(x) { console.log('succeeded with ' + x ) },
function(x) { console.log('errored with ' + x ) },
function() { console.log('completed') }
)
我得到了预期的输出:
succeeded with Hi!
completed
为什么发生错误时它没有完成?
Why does it not complete when an error has occured?
推荐答案
那是因为错误意味着完成,所以与 onCompleted
关联的回调永远不会被调用.您可以在此处查看可观察的 Rxjs 合同(http://reactivex.io/documentation/contract.html) :
That's because an error means completion, so the callback associated to onCompleted
never gets called. You can review here Rxjs contract for observables (http://reactivex.io/documentation/contract.html) :
一个 Observable 可以发出零个或多个 OnNext 通知,每个通知代表一个发出的项目,然后它可以通过 OnCompleted 或 OnError 通知跟随这些发出通知,但不能同时发出这两个通知.在发出 OnCompleted 或 OnError 通知后,它可能不会发出任何进一步的通知.`
对于错误管理,您可以查看:https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/errors.md
For error management, you can have a look at :https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/errors.md
这篇关于RxJS - 发生错误时 observable 不会完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!