zl程序教程

您现在的位置是:首页 >  工具

当前栏目

RxJS mergeMap 学习笔记

2023-09-14 09:04:00 时间

https://www.learnrxjs.io/learn-rxjs/operators/transformation/mergemap

This operator is best used when you wish to flatten an inner observable but want to manually control the number of inner subscriptions.

使用场合:当您希望展平内部 observable 但想要手动控制内部订阅的数量时

For instance, when using switchMap each inner subscription is completed when the source emits, allowing only one active inner subscription. In contrast, mergeMap allows for multiple inner subscriptions to be active at a time. Because of this, one of the most common use-case for mergeMap is requests that should not be canceled, think writes rather than reads. Note that if order must be maintained concatMap is a better option.

例如,当使用 switchMap 时,每个内部订阅在源发出时完成,只允许一个活动的内部订阅。 相比之下,mergeMap 允许同时激活多个内部订阅。 因此,mergeMap 最常见的用例之一是不应取消的请求,认为是写入而不是读取。 请注意,如果必须维护顺序,则 concatMap 是更好的选择。

注意内存泄漏问题。

Be aware that because mergeMap maintains multiple active inner subscriptions at once it’s possible to create a memory leak through long-lived inner subscriptions. A basic example would be if you were mapping to an observable with an inner timer, or a stream of dom events. In these cases, if you still wish to utilize mergeMap you may want to take advantage of another operator to manage the completion of the inner subscription, think take or takeUntil. You can also limit the number of active inner subscriptions at a time with the concurrent parameter

由于 mergeMap 一次维护多个活动的内部订阅,因此可能会通过长期存在的内部订阅造成内存泄漏。 一个基本示例是,如果您要映射到具有内部计时器的 observable 或 dom 事件流。 在这些情况下,如果您仍然希望使用 mergeMap,您可能希望利用另一个操作符来管理内部订阅的完成,考虑 take 或 takeUntil。 您还可以使用 concurrent 参数限制一次活动内部订阅的数量。