Skip to content

Instantly share code, notes, and snippets.

@btroncone
Last active April 19, 2022 22:29
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save btroncone/fe9d9aaf457f2ebd72c4624e34d664f8 to your computer and use it in GitHub Desktop.
Save btroncone/fe9d9aaf457f2ebd72c4624e34d664f8 to your computer and use it in GitHub Desktop.
Cleaning up subscriptions in Angular

Which do you prefer?

Adding to common sub, calling subscription.unsubscribe() in ngOnDestroy:

export class MyComponent {
  private _subscription: Subscription;
  
  ngOnInit() {
    this._subscription = myObservable
      .mergeMap(something)
      .subscribe(
        // some extra logic here
      );
      
    const anotherSubscription = myOtherObservable
      .mergeMap(somethingElse)
      .subscribe(
        // some extra logic here
      );
      
    this._subscription.add(anotherSubscription);
  }
  
  ngOnDestroy() {
    this._subscription.unsubscribe();
  }
}

Using takeUntil and private Subject, calling next in ngOnDestroy:

export class MyComponent {
  private _onDestroy = new Subject();
  
  ngOnInit() {
    myObservable
      .mergeMap(something)
      .takeUntil(this._onDestroy)
      .subscribe(
        // some extra logic here
      );
      
    myOtherObservable
      .mergeMap(somethingElse)
      .takeUntil(this._onDestroy)
      .subscribe(
        // some extra logic here
      );
  }
  
  ngOnDestroy() {
    this._onDestroy.next();
  }
}

*Note: takeUntil will also complete the observable before unsubscribing (thanks @GerardSans)

@safalpillai
Copy link

@Totati
Copy link

Totati commented Nov 15, 2020

How about subsink? https://github.com/wardbell/subsink

We used to use it, but we went back using takeUntil

@safalpillai
Copy link

We used to use it, but we went back using takeUntil

Any particular reason or advantage for opting for takeUntil over Subsink?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment