Get all current (active) subscriptions

后端 未结 7 1093
清歌不尽
清歌不尽 2021-02-12 20:58

Is it possible to get all the \"active\" subscriptions without storing them manually?

I\'d like to unsubscribe all of the \"active\" subscriptions and don\'

7条回答
  •  无人及你
    2021-02-12 21:32

    You can inherit a Base component that implements the OnDestroy interface and keep an array to store all the Subscription and finally on destroy you can find the object with the instanceof Subscription and unsubscribe all. Let me write the code below.

    1. Create a Base class that implements OnInit, ODestroy
    export class BaseComponent implements OnInit, OnDestroy {
    
      subscriptions: Subscription[] = [];
    
      ngOnInit(): void {
      }
    
      ngOnDestroy(): void {
        console.log('OnDestory - Baselass');
        this.subscribers.forEach(sub => {
          sub.unsubscribe();
          console.log('Unsub');
        })
      }
    
    
       addObserver(subscription: Subscription) {
          this.subscribers.push(subscription);
       }
    }
    
    1. Create a component and inherit the Base class
    export class SomeComponent extends BaseComponent implements OnInit, OnDestroy {
    
        constructor(private someService: SomeService) {
          super();
        }
    
        ngOnInit(): void {
          super.ngOnInit();
        }
    
        ngOnDestroy(): void {
          super.ngOnDestroy()
        }
    
        private initObservers() {
          super.addObserver(this.someService.someObservable$.subscribe(res => {
    
          }));
        }
    
        
    }
    

    That's it, You don't now need to worry about unsubscribing a Subscription manually, BaseComponent with taking care of that.

    Important point:- Pass the subscription to superclass is necessary, which keeps the list and unsubscribe all Subscriptions on component destroy lifecycle event.

    super.addObserver(this.someService.someObservable$.subscribe(res => {
    
    }));
    

    Thanks!!

提交回复
热议问题