Angular/RxJs When should I unsubscribe from `Subscription`

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

    For handling subscription I use a "Unsubscriber" class.

    Here is the Unsubscriber Class.

    export class Unsubscriber implements OnDestroy {
      private subscriptions: Subscription[] = [];
    
      addSubscription(subscription: Subscription | Subscription[]) {
        if (Array.isArray(subscription)) {
          this.subscriptions.push(...subscription);
        } else {
          this.subscriptions.push(subscription);
        }
      }
    
      unsubscribe() {
        this.subscriptions
          .filter(subscription => subscription)
          .forEach(subscription => {
            subscription.unsubscribe();
          });
      }
    
      ngOnDestroy() {
        this.unsubscribe();
      }
    }
    

    And You can use this class in any component / Service / Effect etc.

    Example:

    class SampleComponent extends Unsubscriber {
        constructor () {
            super();
        }
    
        this.addSubscription(subscription);
    }
    

提交回复
热议问题