I have a question about one of the common pattern for the unsubscribing with the takeUntil operator for Angular and RxJs. In this article, it 's under the third position. For example, we have such code in a component class:
private destroy$: Subject<boolean> = new Subject();
ngOnInit() {
this.control.
.pipe(takeUntil(this.destroy$)
.subscribe(doSmthngFunc);
}
ngOnDestroy() {
this.destroy$.next(true);
// Which next line of code is correct?
// this.destroy$.complete() // this one?
// this.destroy$.unsubscribe() // or this one?
}
The first line this.destroy$.next(true) is totally clear. But the second is not. If we look into the realization of these methods, we find that they have somewhat similar behavior. complete(): unsubscribe():
As I understand semantically complete() is preferable, because we call next() for the first and the last time during the component life and then we finished with this Subject, treated as Observable and can invoke complete(). These methods belong to the observer and unsubscribe belong to the observable, and we have no subscriptions to unsubscribe from. But under the hood, these methods have a similar code:
this.isStopped = true; // both
this.observers.length = 0; // complete
this.observers = null; // unsubscribe
this.closed = true; // only unsubscribe
Theoretically complete() has delayed effect as it's may invoke complete() on every observer subscribed, but we have no observers on destroy$. So the question - which way is more preferable, less error-prone, and why?
Which next line of code is correct?
comment are redundant. Only thethis.destroy$.next(true);
is necessary. ThetakeUntil
operator is the only subscriber to thedestroy$
subject and it will unsubscribe as soon as thedestroy$
emits thenext
notification. Neithercomplete
norunsubscribe
need to be called. And you almost never really want to callunsubscribe
on a subject - see blog.angularindepth.com/rxjs-closed-subjects-1b6f76c1b63c – cartantbut we have no observers on destroy$
every time you usetakeUntil()
an observer is added. Observers are the things listening. I think you misunderstood the term. – Reactgular