Angular/RxJs When should I unsubscribe from `Subscription`

前端 未结 22 2205
隐瞒了意图╮
隐瞒了意图╮ 2020-11-21 04:56

When should I store the Subscription instances and invoke unsubscribe() during the NgOnDestroy life cycle and when can I simply ignore them?

22条回答
  •  抹茶落季
    2020-11-21 05:34

    The Subscription class has an interesting feature:

    Represents a disposable resource, such as the execution of an Observable. A Subscription has one important method, unsubscribe, that takes no argument and just disposes the resource held by the subscription.
    Additionally, subscriptions may be grouped together through the add() method, which will attach a child Subscription to the current Subscription. When a Subscription is unsubscribed, all its children (and its grandchildren) will be unsubscribed as well.

    You can create an aggregate Subscription object that groups all your subscriptions. You do this by creating an empty Subscription and adding subscriptions to it using its add() method. When your component is destroyed, you only need to unsubscribe the aggregate subscription.

    @Component({ ... })
    export class SmartComponent implements OnInit, OnDestroy {
      private subscriptions = new Subscription();
    
      constructor(private heroService: HeroService) {
      }
    
      ngOnInit() {
        this.subscriptions.add(this.heroService.getHeroes().subscribe(heroes => this.heroes = heroes));
        this.subscriptions.add(/* another subscription */);
        this.subscriptions.add(/* and another subscription */);
        this.subscriptions.add(/* and so on */);
      }
    
      ngOnDestroy() {
        this.subscriptions.unsubscribe();
      }
    }
    

提交回复
热议问题