The main difference is the way of thinking ... and the pattern.
Without takeUntil , when your file grows in size and lines of code, you can get something like this:
private subscription1: Subscription; private subscription2: Subscription; private subscription3: Subscription; private subscription4: Subscription; private subscription5: Subscription; private subscription6: Subscription; ngOnInit() { this.subscription1 = this.service.method().subscribe(...); this.subscription2 = this.service.method().subscribe(...); this.subscription3 = this.service.method().subscribe(...); this.subscription4 = this.service.method().subscribe(...); this.subscription5 = this.service.method().subscribe(...); this.subscription6 = this.service.method().subscribe(...); } ngOnDestroy() { this.subscription1.unsubscribe(); this.subscription2.unsubscribe(); this.subscription3.unsubscribe(); this.subscription4.unsubscribe(); this.subscription5.unsubscribe(); this.subscription6.unsubscribe(); }
Or you can declare a subscription array and click on it.
Both do not seem very convenient, and if you have many methods that contain subscriptions, you wonβt be able to find out if they have unsubscribed or not unless you go to ngOnDestroy .
On the other hand, using Subject more readable:
private onDestroy$ = new Subject<void>(); ngOnInit() { this.service.method().takeUntil(this.onDestroy$).subscribe(...); this.service.method().takeUntil(this.onDestroy$).subscribe(...); this.service.method().takeUntil(this.onDestroy$).subscribe(...); this.service.method().takeUntil(this.onDestroy$).subscribe(...); this.service.method().takeUntil(this.onDestroy$).subscribe(...); this.service.method().takeUntil(this.onDestroy$).subscribe(...); } ngOnDestroy() { this.onDestroy$.next(); this.onDestroy$.complete(); }
Even if the subscriptions are shared across the entire file, you can simply check if takeUntil(this.onDestroy$) present.
It is also closer to the idea of ββRxjs and deals with threads.
Now, to make sure something is not signed, you can simply use the third subscription argument:
this.service.method().takeUntil(this.onDestroy$).subscribe( onNext => ..., onError => ..., onComplete => console.log('stream has been completed') );
If you do not want to invest in the subscription method, you can do this:
this.service.method().takeUntil(this.onDestroy$) .do({ complete => console.log('stream has been completed') }) .subscribe();
If you want to go further, you should read this wonderful article by Ben Lesh : https://medium.com/@benlesh/rxjs-dont-unsubscribe-6753ed4fda87