首页 > 解决方案 > RxJS 订阅管理 - 避免过度订阅

问题描述

如何避免超额订阅?

是否有可用于确保取消订阅任何活动订阅的功能?

clickDown(e) {
  this.mouseMoveSubscription = fromEvent(this.elementRef.nativeElement, 'mousemove')
    .subscribe((e: MouseEvent) => {
      console.log(e);                                          
    });
}

标签: angular

解决方案


假设您没有使用async管道,那么当前接受的模式是使用或者takeUntil管理takeWhile您的订阅onDestroy

例如:

import { Component, OnDestroy, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { takeWhile } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})
export class AppComponent implements OnInit, OnDestroy {
  unsubscribed = false; // <-- When the component loads, subscriptions are all active.

  constructor(private router: Router) { }

  ngOnInit(): void {
    this.router.events
      .pipe(takeWhile(() => !this.unsubscribed)) // <-- Maintain this subscription while the component is not destroyed.
      .subscribe(() => {});
  }

  ngOnDestroy(): void {
    this.unsubscribed = true; // <-- When the component is destroyed, unsubscribe all subscriptions bound to this.unsubscribed.
  }
}

推荐阅读