RxJS 订阅者取消订阅与完成 [英] RxJS Subscriber unsubscribe vs. complete

查看:77
本文介绍了RxJS 订阅者取消订阅与完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 RxJS 文档,并希望确保我了解 Subscriber.unsubscribe()Subscriber.complete() 之间的区别.>

假设我有一个 observable,有两个订阅者,subscriber1 和subscriber2.如果subscriber1 对他们的订阅调用unsubscribe,它将不再收到来自observable 的通知,但subscriber2 会继续收到通知.

.complete() 的文档:

<块引用>

Observer 回调接收来自 Observable 的无值类型 complete 通知.通知观察者 Observable 已完成发送基于推送的通知.

这是否意味着在上面的相同场景中,subscriber1 可以调用 complete 并结束 observable 并停止subscriber1 和subscriber2 的流?

解决方案

订阅者不调用 complete().你可以在一个 Subject 上调用 complete() 或者更常见的是它使用诸如 take()takeWhile(), ...

例如:

const s = new Subject();constsubscriber1 = s.subscribe(...);constsubscriber2 = s.subscribe(...);s.完成();//两个订阅者都会收到完整的通知//或者使用 `take(1)` 操作符,它会为你调用 `complete()`constsubscriber1 = s.take(1).subscribe(...);constsubscriber2 = s.take(1).subscribe(...);s.next(42);//两个订阅者都会收到完整的通知

请注意,对 Subject 调用 complete() 会更改其内部状态,并且无法再次使其不完整,而只是取消订阅订阅者对 Subject 没有影响.

一个类似的问题:Observable finally on Subscribe

I was reading through the RxJS docs and want to make sure I'm understanding the difference between Subscriber.unsubscribe() and Subscriber.complete().

Let's say I have an observable with two subscribers, subscriber1 and subscriber2. If subscriber1 calls unsubscribe on their subscription, it will no longer receive notifications from the observable but subscriber2 will continue to receive them.

The docs for .complete():

The Observer callback to receive a valueless notification of type complete from the Observable. Notifies the Observer that the Observable has finished sending push-based notifications.

Does this mean that in the same scenario above, subscriber1 could call complete and it would end the observable and stop the stream for both subscriber1 and subscriber2?

解决方案

Subscribers don't call complete(). You can call complete() on a Subject or more typically it's called for you "indirectly" using operators such as take(), takeWhile(), ...

For example:

const s = new Subject();
const subscriber1 = s.subscribe(...);
const subscriber2 = s.subscribe(...);
s.complete(); // both subscribers will receive the complete notification

// or with `take(1)` operator it'll call `complete()` for you
const subscriber1 = s.take(1).subscribe(...);
const subscriber2 = s.take(1).subscribe(...);
s.next(42); // both subscribers will receive the complete notification

Note that calling complete() on a Subject changes its inner state and there's no way to make it non-complete again while just unsubscribing a subscriber has no effect on the Subject.

A little similar question: Observable Finally on Subscribe

这篇关于RxJS 订阅者取消订阅与完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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