我正在通读 RxJS 文档并想确保我理解 Subscriber.unsubscribe()
之间的区别。和 Subscriber.complete()
.
假设我有一个包含两个订阅者的可观察对象,subscriber1 和 subscriber2。如果 subscriber1 在其订阅上调用取消订阅,它将不再收到来自 observable 的通知,但 subscriber2 将继续接收它们。
.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.
这是否意味着在上面的相同场景中,subscriber1 可以调用 complete 并且它会结束 observable 并停止 subscriber1 和 subscriber2 的流?
最佳答案
订阅者不调用 complete()
。您可以在 Subject 上调用 complete()
,或者更典型的是使用 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
请注意,在 Subject 上调用 complete()
会更改其内部状态,并且无法使其再次变为非完整状态,而仅取消订阅订阅者对 Subject 没有影响。
一个类似的问题:Observable Finally on Subscribe
关于javascript - RxJS 订阅者取消订阅与完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48771350/