4

I am using the accepted pattern for unsubscribing my Subscriptions:

private ngUnsubscribe: Subject<void> = new Subject();

ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
}

However, I am having issues with the following rxjs code using takeUntil and combineLatest:

this.observableA$.pipe(
    takeUntil(this.ngUnsubscribe),
    combineLatest(
        this.observableB$,
        this.observableC$
    )
).subscribe(([A, B, C]) => {
    // do some work   
})

This subscription seems to be persisting, as I can see the code firing multiple times after the component is destroyed and re-initialized. Any help would be greatly appreciated.

ElliotSchmelliot
  • 7,322
  • 4
  • 41
  • 64

1 Answers1

5

Your inner observableB and observableC aren't unsubscribed. Try rearranging your operators:

combineLatest(
    this.observableB$,
    this.observableC$
),
takeUntil(this.ngUnsubscribe)
Joshua Chan
  • 1,797
  • 8
  • 16
  • Yep. The last returned observable is subscribed to first, so the `takeUntil` should be as late as possible in the `pipe` to be as early as possible in the `subscribe` chain. +1. – cartant May 25 '18 at 20:15
  • Just tested swapping the operators and it works as expected! Thanks! – ElliotSchmelliot May 25 '18 at 21:04