Angular RxJS可观察:takeUntil与通过订阅退订 [英] Angular RxJS Observable: takeUntil vs. unsubscribe with a Subscription

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

问题描述

有几种方法可以取消订阅Angular组件上的可观察对象(通过使用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 take

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可观察:takeUntil与通过订阅退订的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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