Why does Rxjs unsubscribe on error?

一世执手 提交于 2019-11-30 13:01:29

Rx observables follow the grammar next*(error|complete)?, meaning that they can produce nothing after error or complete notification has been delivered.

An explanation of why this matters can be found from Rx design guidelines:

The single message indicating that an observable sequence has finished ensures that consumers of the observable sequence can deterministically establish that it is safe to perform cleanup operations.

A single failure further ensures that abort semantics can be maintained for operators that work on multiple observable sequences.

In short, if you want your observers to keep listening to the subject after a server error has occurred, do not deliver that error to the subject, but rather handle it in some other way (e.g. use catch, retry or deliver the error to a dedicated subject).

martin

Every Observable emits zero or more next notifications and one error or complete but never both.

For this reason, Subjects have internal state.

Then it depends how you construct your chain. For example you can use retry() to resubscribe to its source Observable on error.

Or when you pass values to your Subject you can send only next notifications and ignore the other two:

.subscribe(v => subject.next(v));

Or if you want to throw error when the user is null you can use any operator that captures exceptions and sends them as error notifications. For example like this:

.map(v => {
    if (v === null) {
        throw new Error("It's broken");
    }
    return v;
})

Anyway it's hard to give more precise advice without any code.

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