如何计算每个组件或页面留下的所有未完成的订阅?

时间:2018-05-24 13:27:05

标签: angular ionic-framework rxjs

  1. 在Ionic app中,页面只是一个组件。
  2. 我想查看每个页面未完成的订阅总额。这意味着他们正在做不需要的背景工作。
  3. 假设我有pageChanged$通知页面何时更改。
  4. 我目前的尝试

        let activeSubscriptions = 0;
        let originalUnsubscribe = Subscription.prototype.unsubscribe;
        Subscription.prototype.unsubscribe = function (...args) {
          activeSubscriptions--;
          return originalUnsubscribe.call(this, ...args);
        }
        let originalSubscribe = Observable.prototype.subscribe;
        Observable.prototype.subscribe = function (...args) {
          activeSubscriptions++;
          return originalSubscribe.call(this, ...args);
        }
    
        let pageChanged$ = new Subject<string>();
        let lastActiveSubs = 0;
        let lastName = 'Start';
        pageChanged$
          .subscribe((pageName) => {
            console.log(`${lastName} += ${activeSubscriptions - lastActiveSubs}`)
            lastActiveSubs = activeSubscriptions
            lastName = pageName
          })
    
    1. 您能提供更好的方法或改进吗?
    2. 当一个页面&#39; A&#39;被推到页面顶部&#39; B&#39;,是页面&#39; B&#39;销毁或缓存?

1 个答案:

答案 0 :(得分:0)

我所做的是创建一个订阅数组,其中有一个或多个Observables要监听。 每当我创建订阅时,我都会将其添加到该数组中。然后,当命中ngOnDestroy时,我会浏览所有这些并取消订阅:

@IonicPage()
@Component({
  selector: 'my-selector',
  templateUrl: 'myselector.html'
})
export class APage {
   subscriptions : Array<Subscription> = new Array<Subscription>();

   ngOnInit() {
      let a_new_subscription = someObservable.subscribe(someFunction);
      this.subscriptions.push(a_new_subscription);
      //Add as many subscriptions as created
   }

   //...

   ngOnDestroy(){
     this.subscriptions.forEach(
        subscription => {
           subscription.unsubscribe();   
        }
     )
   }
}