问题描述
我正在阅读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()
:
这是否意味着在上面的相同场景中,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()$ c $等运算符间接调用它c>,
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订阅者取消订阅与完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!