Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS Subscriber unsubscribe vs. complete

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?

like image 500
BrentShanahan Avatar asked Feb 13 '18 16:02

BrentShanahan


People also ask

Does unsubscribe call complete?

Calling unsubscribe() itself does not call complete method. Angular async pipe is an example of calling unsubscribe .

Do I need to unsubscribe from a completed Observable RxJS?

No, you don't need to unsubscribe from an observable you know has completed. If you look at the source code of the RxJS toPromise() function, you'll see a subscribe, but no unsubscribe. That's because it is not necessary, you know the observable is completed.

Why is unsubscribing important in RxJS?

Specifically, we must unsubscribe before Angular destroys the component. Failure to do so could create a memory leak.


1 Answers

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

like image 174
martin Avatar answered Sep 18 '22 15:09

martin