Get all current (active) subscriptions

老子叫甜甜 提交于 2019-12-09 14:42:48

问题


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't want to reference each of them in an array or a variable.


回答1:


I depends on whether you're using a Subject or an Observable but there's probably no way to do this "automatically".

Observables

I don't think you can have such thing as "subscribed Observable" because you either store an Observable or Subscription:

const source = Observable.of(...)
  .map(...);

const subscription = source
  .subscribe();

Here source represents an Observable and subscription represents a single subscription.

Note that you can have a Subscription instance that stores multiple other subscriptions:

const subscriptions = new Subscription();

const sub1 = Observable...subscribe();
const sub2 = Observable...subscribe();
const sub3 = Observable...subscribe();

subscriptions.add(sub1).add(sub2).add(sub3);

// Then unsubscribe all of them with a single 
subscriptions.unsubscribe();

Subjects

If you're using Subjects they do have the unsubscribe method themselves, see https://github.com/ReactiveX/rxjs/blob/master/src/Subject.ts#L96.

However be aware that this makes the Subject "stopped", for more info see https://medium.com/@martin.sikora/rxjs-subjects-and-their-internal-state-7cfdee905156




回答2:


Yeap. Just call .observers property if you is using Subject object of the rxjs.

Hope this helps.




回答3:


One of the options is to use takeUntil in combination with Subject to stop all (Observable) subscriptions.

terminator$: Subject<boolean> = new Subject();

Observable.timer(1000)
  .do(i => console.log(`timer 1: ${i}`))
  .takeUntil(terminator$)
  .subscribe();

Observable.timer(5000)
  .do(i => console.log(`timer 2: ${i}`))
  .takeUntil(terminator$)
  .subscribe();

const stopSubscriptions = () => terminator$.next(true);



回答4:


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<T> {
    subscribeAndGuard: typeof subscribeAndGuard;
  }
}

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




回答5:


You can just store one Subscription, and add to it.

private _subscriptions = new Subscription();   // yes you can do this!

Then add to it

_subscriptions.add(
    this.layoutManager.width$.subscribe((w) => {

        // any nested subscriptions can also use this mechanism
        _subscriptions.add(...);
    });

Then in ngOnDestroy() you just call _subscriptions.unsubscribe();.

I've been trying to make a 'clever' way to do this, but to be frank I've overengineered it quite a bit (including logging) and this is the simplest way I've come across.




回答6:


With this decorator you shouldn't put the unsubscribe(), this is done automatically.

For use this you only need declare onDestroy, you don't need to put anything in this.

It is very easy to use, I encourage you to use it.

Npm installation

Official documentation



来源:https://stackoverflow.com/questions/47040664/get-all-current-active-subscriptions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!