Hot vs Cold Observables [英] Hot vs Cold Observables

查看:26
本文介绍了Hot vs Cold Observables的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 RxJS 中,热 observable 是使用外部生产者的 observable,而冷 observable 使用本地生产者(参见例如 RxJS Hot vs Cold Observable by Ben Lesh).

In RxJS hot observables are observables which use an external producer, but a cold observable use a local producer (see e.g. RxJS Hot vs Cold Observable by Ben Lesh).

Angular HttpClient.post 使用冷 observables 发送数据并在您拨打电话时重复.

Angular HttpClient.post uses cold observables to send data and repeats whenever you make a call.

Angular 有没有办法知道一个特定的方法是使用热观察还是冷观察?

Is there any way in Angular to know whether a specific method uses a hot or cold observable?

推荐答案

没有.文档是最安全的选择.另外,我不同意@martin 的评论,这绝对重要.您需要小心冷观察,以避免重新订阅和重新发布昂贵的操作(例如,通过使用多播或将结果保存到主题).

No. Documentation is the safest bet. Also, I disagree with @martin's comment, it absolutely does matter. You need to be careful with cold observables to avoid resubscribing and reissuing expensive operations (e.g. by using multicasting or saving off the result to a subject).

您还必须依靠文档来了解 observable 何时/如何完成.例如,您无需担心取消订阅 HttpClient.post,因为您知道它会完成.但是,如果您在 HttpClient 周围使用某种包装器,它通过缓存的主题提供请求,您可能无法再完成.每个组件都会生成一个新订阅,并且在组件销毁后,该订阅将成为从 Subject 到组件的引用,因此该组件不会被垃圾回收,最终会导致内存泄漏.

You also have to rely on the documentation to know when/how an observable completes. For example, you don't need to ever worry about unsubscribing from HttpClient.post because you know it will complete. However, if you're using some kind of wrapper around HttpClient which serves requests via a cached Subject you might not complete anymore. Every component will generate a new subscription and, after the component is destroyed, that subscription will be a reference from the Subject to the component so the component won't be garbage collected and you will end up with a memory leak.

没有办法以编程方式知道你订阅了什么样的 Observable,它是否会完成.

There is no way to programmatically know what kind of Observable you've subscribed to, whether it will complete or not.

一般来说,这是通过聪明地完成你的 observables 和使用诸如 takeUntilSubscription 之类的工具来清理订阅到长期运行的非完成 observables 或昂贵的可观察工作负载.

In general this is managed both by being smart about completing your observables and by using tools like takeUntil or Subscription to clean up subscriptions to long running non-completing observables or expensive observable workloads.

*实际上,澄清一下,您需要小心所有的可观察值,而不仅仅是冷的可观察值.Hot observables 也会产生昂贵的工作负载.

* Actually, to clarify, you need to be careful with all observables, not just cold observables. Hot observables can generate expensive workloads too.

*更新示例删除 ActivatedRoute,因为这些 observable 在组件销毁时完成.

* Update example removing ActivatedRoute as those observables are completed when the component is destroyed.

这篇关于Hot vs Cold Observables的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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