In a previous post, I suggested using a decorator to unsubscribe. I’m back to say, eh, naw, not for me.

The post in question was here..

It’s fine. It will work, which is the important thing.

I’ve since discovered that there is a nicer way of doing things, which is using the takeUntil operator.

If a subscription is tied to takeUntil, when the condition is satisfied - in this case, a Subject that we will complete when ngOnDestroy is called - the subscription is automatically unsubscribed.

It’s less code, and it’s obvious what is going on.

export class SomeComponent implements OnInit, OnDestroy {
  someLocalData: string;
  private destroyed$ = new Subject();
  constructor(private someService: SomeService) {}
 
  ngOnInit() {
    this.someService.getSomeData()
      .pipe(takeUntil(this.destroyed$))
      .subscribe((data: string) => this.someData = data);
  }
 
  ngOnDestroy(): void {
    this.destroyed$.next();
    this.destroyed$.complete();
  }
}

Every observable you subscribe to, you just tack on the .takeUntil.

It almost reads like English - subscribe to this and keeping taking elements until this other thing is destroyed.

Anyway, there are a few ways to unsubscribe to Observables. This article here was great, showing the different ways of unsubscribing.

Ben Lesh’s excellent article, Rxjs: Don’t Unsubscribe, seems to be the one the touchstone for a different perspective on unsubscribing, and it’s a must read.