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

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

问题描述

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

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

假设我有两个订阅者,即subscriber1和subscriber2的observable。如果subscriber1呼叫取消订阅他们的订阅,它将不再接收来自observable的通知,但subscriber2将继续接收它们。

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.

的文档。 complete()


Observer回调,用于从Observable接收类型为complete的无值通知。通知观察者Observable已完成发送基于推送的通知。

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.

这是否意味着在上面的相同场景中,subscriber1可以调用完成并结束可观察并停止订阅者1和订阅者2的流?

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?

推荐答案

订阅者不会调用完成()。您可以在主题上调用 complete(),或者通常使用 take() takeWhile(),...

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(), ...

例如:

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

请注意,调用 complete()主题上的更改其内部状态,并且无法再次取消订阅,而只是取消订阅订阅者对主题没有影响。

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.

一个类似的问题:最后订阅可观察

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

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