最后在订阅上观察 [英] Observable Finally on Subscribe

查看:15
本文介绍了最后在订阅上观察的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据这篇文章onCompletesubscribeonError 函数是互斥的.

According to this artcle, onComplete and onError function of the subscribe are mutually exclusive.

意味着 onErroronComplete 事件将在我的 subscribe 中触发.
我有一个逻辑块,无论我收到错误还是成功完成信息流,都需要执行该逻辑块.

Meaning either onError or onComplete events will fire up in my subscribe.
I have a logic block which needs to be executed whether I receive an error, or I finish my steam of information successfully.

我在 python 中查找了类似 finally 的东西a>,但我发现的只是 finally 需要附加到我创建的可观察对象.

I looked up for something like finally in python, but all I found is finally which needs to be attached to the observable I create.

但我只想在订阅时执行该逻辑,并且在流结束后,无论是成功还是出现错误.

But I want to to do that logic only when I subscribe, and after the stream has ended, whether successfully or with an error.

有什么想法吗?

推荐答案

这个操作符当前的pipable"变体叫做 finalize()(从 RxJS 6 开始).较旧且现已弃用的补丁"运算符称为 finally()(直到 RxJS 5.5).

The current "pipable" variant of this operator is called finalize() (since RxJS 6). The older and now deprecated "patch" operator was called finally() (until RxJS 5.5).

我认为 finalize() 运算符实际上是正确的.你说:

I think finalize() operator is actually correct. You say:

仅在我订阅时和流结束后执行该逻辑

do that logic only when I subscribe, and after the stream has ended

我认为这不是问题.如果需要,您可以拥有一个 source 并在订阅之前使用 finalize().这样你就不需要总是使用finalize():

which is not a problem I think. You can have a single source and use finalize() before subscribing to it if you want. This way you're not required to always use finalize():

let source = new Observable(observer => {
  observer.next(1);
  observer.error('error message');
  observer.next(3);
  observer.complete();
}).pipe(
  publish(),
);

source.pipe(
  finalize(() => console.log('Finally callback')),
).subscribe(
  value => console.log('#1 Next:', value),
  error => console.log('#1 Error:', error),
  () => console.log('#1 Complete')
);

source.subscribe(
  value => console.log('#2 Next:', value),
  error => console.log('#2 Error:', error),
  () => console.log('#2 Complete')
);

source.connect();

这会打印到控制台:

#1 Next: 1
#2 Next: 1
#1 Error: error message
Finally callback
#2 Error: error message

2019 年 1 月:针对 RxJS 6 更新

Jan 2019: Updated for RxJS 6

这篇关于最后在订阅上观察的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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