Angular RxJS Observable:takeUntil 与使用订阅取消订阅 [英] Angular RxJS Observable: takeUntil vs. unsubscribe with a Subscription

查看:24
本文介绍了Angular RxJS Observable:takeUntil 与使用订阅取消订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有几种方法可以取消订阅 Angular 组件上的 observables(通过使用 ngOnDestroy).应首选以下哪个选项?为什么(例如技术原因、性能等)?

There are several ways to unsubscribe from observables on Angular components (by using ngOnDestroy). Which option below should be preferred and why (e.g. technical reasons, performance, etc.)?

使用 RxJS takeUntil 取消订阅

Using RxJS takeUntil to unsubscribe

@Component({
  selector: "app-flights",
  templateUrl: "./flights.component.html"
})
export class FlightsComponent implements OnDestroy, OnInit {
  private readonly destroy$ = new Subject();

  public flights: FlightModel[];

  constructor(private readonly flightService: FlightService) {}

  ngOnInit() {
    this.flightService
      .getAll()
      .pipe(takeUntil(this.destroy$))
      .subscribe(flights => (this.flights = flights));
  }

  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }
}

选项 2:.unsubscribe()

显式调用 .unsubscribe(),例如通过使用单独的订阅实例

Option 2: .unsubscribe()

Explict call .unsubscribe(), e.g. by using a separate subscription instance

@Component({
  selector: "app-flights",
  templateUrl: "./flights.component.html"
})
export class FlightsComponent implements OnDestroy, OnInit {
  private readonly subscriptions = new Subscription();

  public flights: FlightModel[];

  constructor(private readonly flightService: FlightService) {}

  ngOnInit() {
    const subscription = this.flightService
      .getAll()
      .subscribe(flights => (this.flights = flights));

    this.subscriptions.add(subscription);
  }

  ngOnDestroy() {
    this.subscriptions.unsubscribe();
  }
}

选项 3:takeWhile

使用 RxJS takeWhile 取消订阅

Option 3: takeWhile

Using RxJS takeWhile unsubscribe

推荐答案

  • 选项 1:清洁 &明确的.像魅力一样工作
  • 选项 2:更多程序化,更少流化.奇迹般有效.请注意,您的流不会收到可能导致意外行为的完成"事件
  • 选项 3:takeWhile - 将保持订阅,直到创建发射,然后评估 takeWhile.这可能会导致意外行为.尽管如此,最终还是有效
  • TLDR;这里没有错.选择您所看到的适合您的需求并传达您的意图.

    TLDR; there is no wrong here. Choose what you see fits your needs and communicates your intent.

    Ben Lesh 还写了一篇关于取消订阅的不同方式的好文章https://medium.com/@benlesh/rxjs-dont-unsubscribe-6753ed4fda87

    Ben Lesh has also written quite a good post about the different ways to unsubscribe https://medium.com/@benlesh/rxjs-dont-unsubscribe-6753ed4fda87

    他的意见:

    您可能应该使用像 takeUntil 这样的操作符来管理您的 RxJS 订阅.根据经验,如果您看到在一个组件中管理两个或更多订阅,您应该想知道是否可以更好地组合这些订阅.

    You should probably be using operators like takeUntil to manage your RxJS subscriptions. As a rule of thumb, if you see two or more subscriptions being managed in a single component, you should wonder if you could be composing those better.

    这篇关于Angular RxJS Observable:takeUntil 与使用订阅取消订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆