4

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

Jem
  • 6,226
  • 14
  • 56
  • 74
  • 2
    See https://stackoverflow.com/questions/42490265/rxjs-takeuntil-angular-components-ngondestroy and https://stackoverflow.com/questions/45333939/angular-what-is-the-preferred-way-to-terminate-observables and https://stackoverflow.com/questions/40563065/difference-between-unsubscribe-to-take1 – martin Feb 20 '18 at 15:51
  • I think, suppose you've multiple subscriptions and you need to control all of them manually, then using `takeUntil` approach is good way to deal with it. For 2nd question about how to confirm how `takeUntil` work, you can read the source code, or create simple interval stream, then combine with `takeUntil` after amount of time. – Tiep Phan Feb 20 '18 at 15:53
  • @TiepPhan: it's not a question of basic idea of how `takeUntil` works. it's about detail: does it really unsubscribe, or does it just stop forwarding items? that's a bit harder to test than just creating a simple stream – quetzalcoatl Jul 24 '18 at 10:06

1 Answers1

1

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

Jem
  • 6,226
  • 14
  • 56
  • 74