Search code examples
angularrxjsobservablesubscription

Unsubscribing to rxjs observable using takeUntil and combineLatest not working


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.


Solution

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

    combineLatest(
        this.observableB$,
        this.observableC$
    ),
    takeUntil(this.ngUnsubscribe)