Reputation: 6406
I'm facing the following bit of code inside a component.
private _destroy$ = new Subject<null>();
// ...
ngOnInit() {
this.someStream$
.pipe(filter(a=> a !== null), takeUntil(this._destroy$))
.subscribe(a => { });
}
ngOnDestroy() {
this._destroy$.next();
this._destroy$.complete();
}
Googling this matter gave me one contrasted opinion regarding declarative code vs imperative, the latter being favoured by reactive architecture.
With that in mind, my question is: Compared to the way I've always approached the same case (illustrated with a snippet bellow), is there any other aspect than declarative vs imperative code? Also, how to confirm that the first approach ends up unsubscribing from the stream when takeUntil's
predicate is complete?
private _subscription: Subscription = null;
// ...
ngOnInit() {
this._subscription = this.someStream$
.pipe(filter(a=> a !== null) )
.subscribe(a => { });
}
ngOnDestroy() {
this._subscription && this._subscription.unsubscribe();
}
Appart from
Upvotes: 4
Views: 4507
Reputation: 6406
Apparently, the takeUntil will send a "complete" signal to the subscribing party, allowing it to complete. This causes an unsubscribe.
Upvotes: 1