发生错误时,rxjs observable无法完成 [英] rxjs observable doesn't complete when an error occurs

查看:120
本文介绍了发生错误时,rxjs observable无法完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我从头开始创建一个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通知后,它可能不会再发出任何通知。

An Observable may make zero or more OnNext notifications, each representing a single emitted item, and it may then follow those emission notifications by either an OnCompleted or an OnError notification, but not both. Upon issuing an OnCompleted or OnError notification, it may not thereafter issue any further notifications.`

对于错误管理,你可以看看at:
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无法完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆