Rxjs number of observable subscriptions

前端 未结 3 467
南方客
南方客 2021-01-01 14:47

In my Angular 2 app i have many observables and subscriptions. Ofcourse I should unsubscribe when I leave the page, but i\'m trying to find out if it\'s possible to get the

3条回答
  •  春和景丽
    2021-01-01 15:14

    The following utility function may help...

    function subscriberCount(sourceObservable: Observable, description: string) {
      let counter = 0;
      return Observable.create((subscriber: Subscriber) => {
        const subscription = sourceObservable.subscribe(subscriber);
        counter++;
        console.log(`${description} subscriptions: ${counter}`);
    
        return () => {
          subscription.unsubscribe();
          counter--;
          console.log(`${description} subscriptions: ${counter}`);
        }
      });
    }
    

    Use it like this:

    const timer$ = subscriberCount(Observable.timer(1000), 'Timer');
    

    And the console will log whenever the subscriber count changes

提交回复
热议问题