Get all current (active) subscriptions

后端 未结 7 1094
清歌不尽
清歌不尽 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:36

    I think the basic problem is that an Observable (with exception of Subject and derivatives) does not keep a reference to it's observers.

    Without built-in references, you need to handle them externally in some form.

    I think the best you could achieve is to create a reusable subscription 'override' to wrap the mechanism, although I doubt it's worth it.

    import { Observable } from 'rxjs/Observable';
    import { Subscription } from 'rxjs/Subscription';
    
    const subscribeAndGuard = function(component, fnData, fnError = null, fnComplete = null) {
    
      // Define the subscription
      const sub: Subscription = this.subscribe(fnData, fnError, fnComplete);
    
      // Wrap component's onDestroy
      if (!component.ngOnDestroy) {
        throw new Error('To use subscribeAndGuard, the component must implement ngOnDestroy');
      }
      const saved_OnDestroy = component.ngOnDestroy;
      component.ngOnDestroy = () => {
        console.log('subscribeAndGuard.onDestroy');
        sub.unsubscribe();
        // Note: need to put original back in place
        // otherwise 'this' is undefined in component.ngOnDestroy
        component.ngOnDestroy = saved_OnDestroy;
        component.ngOnDestroy();
    
      };
    
      return sub;
    };
    
    // Create an Observable extension
    Observable.prototype.subscribeAndGuard = subscribeAndGuard;
    
    // Ref: https://www.typescriptlang.org/docs/handbook/declaration-merging.html
    declare module 'rxjs/Observable' {
      interface Observable {
        subscribeAndGuard: typeof subscribeAndGuard;
      }
    }
    

    Ref this question Angular/RxJs When should I unsubscribe from Subscription

提交回复
热议问题