Do you have a bunch of observable subscriptions in your code? Are you finding it a pain to have to go through the mind-numbing pattern of making sure you’re unsubscribing to them in the ngOnDestroy life-cycle event? You are unsubscribing, right?

EDIT -> yeesh. In an earlier version, I claimed that you didn’t have to unsubscribe. That’s not quite true - as per the example on the Github, if you’re building with –prod, you’ll have to explicitly have an ngOnDestroy() method, although it doesn’t have to have anything in it. If you don’t include it, despite the decorator adding it, it’ll be vaporized by –prod optimizations.

  // If you work with AOT this method must be present, even if empty! 
  // Otherwise 'ng build --prod' will optimize away any calls to ngOnDestroy, 
  // even if the method is added by the @AutoUnsubscribe decorator
  ngOnDestroy() {
    // You can also do whatever you need here
  }

If you’re not, there’s a possibility you’ve got a memory leak problem.

Leak!

You don’t want that, do you?

Typically, if you’ve got some observables, the way you’d handle the unsubscribe is something like this:

@Component({
  selector: 'Customer',
  template: `...`,
})
export class CustomerComponent {
  private subscriptions: Subscription = new Subscription();
  customerDetails: CustomerDetails;
  
  constructor( private customerDetailsService: CustomerDetailsService, private customerAlert: CustomerAlertService ) {}
  
  ngOnInit() {
    const sub1 = this.customerDetailsService.getCustomerDetails(id).subscribe( details => this.customerDetails = details);
    const sub2 = this.customerAlertService.onCustomerAlert.subscribe((alert) => console.log(alert));
    this.subscriptions.add(sub1).add(sub2);
  }

  ngOnDestroy() {
    subscriptions.unsubscribe();
  }

}

Kind of ugly, kind of annoying, right?

There’s a better way: using a custom Angular class decorator! Then, you can get rid of all that tracking of each subscription and doing anything in onDestroy, and your code will look like this:

@Component({
  selector: 'Customer',
  template: `...`,
})
@AutoUnsubscribe
export class CustomerComponent {
  private subscriptions: Subscription = new Subscription();
  customerDetails: CustomerDetails;
  
  constructor( private customerDetailsService: CustomerDetailsService, private customerAlert: CustomerAlertService ) {}
  
  ngOnInit() {
    subscriptions.add(this.customerDetailsService.getCustomerDetails(id).subscribe( details => this.customerDetails = details));
    subscriptions.add(this.customerAlertService.onCustomerAlert.subscribe((alert) => console.log(alert)));
  }

  ngOnDestroy(){}
}

Nice, right?

Cleaner, simpler, no more running through the same pattern, and no more memory leaks.

Check out Netanel Basal’s excellent article here

Check out the Github for the latest version of his awesome decorator here