Angular/RxJs When should I unsubscribe from `Subscription`

前端 未结 22 2190
隐瞒了意图╮
隐瞒了意图╮ 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:19

    You can use latest Subscription class to unsubscribe for the Observable with not so messy code.

    We can do this with normal variable but it will be override the last subscription on every new subscribe so avoid that, and this approach is very much useful when you are dealing with more number of Obseravables, and type of Obeservables like BehavoiurSubject and Subject

    Subscription

    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.

    you can use this in two ways,

    • you can directly push the subscription to Subscription Array

       subscriptions:Subscription[] = [];
      
       ngOnInit(): void {
      
         this.subscription.push(this.dataService.getMessageTracker().subscribe((param: any) => {
                  //...  
         }));
      
         this.subscription.push(this.dataService.getFileTracker().subscribe((param: any) => {
              //...
          }));
       }
      
       ngOnDestroy(){
          // prevent memory leak when component destroyed
          this.subscriptions.forEach(s => s.unsubscribe());
        }
      
    • using add() of Subscription

      subscriptions = new Subscription();
      
      this.subscriptions.add(subscribeOne);
      this.subscriptions.add(subscribeTwo);
      
      ngOnDestroy() {
        this.subscriptions.unsubscribe();
      }
      

    A Subscription can hold child subscriptions and safely unsubscribe them all. This method handles possible errors (e.g. if any child subscriptions are null).

    Hope this helps.. :)

提交回复
热议问题