Angular RxJS可观察:takeUntil与通过订阅退订

编程入门 行业动态 更新时间:2024-10-17 13:32:59
本文介绍了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: "./flightsponent.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$plete(); } }

选项2:.unsubscribe()

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

Option 2: .unsubscribe()

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

@Component({ selector: "app-flights", templateUrl: "./flightsponent.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/@benlesh/rxjs-dont-unsubscribe-6753ed4fda87

    Ben Lesh has also written quite a good post about the different ways to unsubscribe medium/@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与通过订阅退订

本文发布于:2023-11-27 23:28:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1640030.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:退订   Angular   RxJS   takeUntil

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!