简体   繁体   中英

Angular + RxJS: use of takeUntil vs simple unsubscribe?

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

Apparently, the takeUntil will send a "complete" signal to the subscribing party, allowing it to complete. This causes an unsubscribe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM