问题描述
RxJS和IxJS有什么区别,我什么时候想在另一个上使用?
从IxJS文档中:
浏览文档后,唯一的主要区别似乎是 IxJS中的Iterables 和 RxJS中的Observables 的概念.
After going through the docs, the only major difference seems to be the concept of Iterables in IxJS and Observables in RxJS.
Iterables和Observables都可以同步或异步执行,并且与几乎相同的from
创建者函数配对时,IxJS的.forEach
本质上与RxJS的.subscribe
方法相同.唯一的不同是IxJS的.forEach
方法是可选的,因为您可以改用命令式for-of
.
Both Iterables and Observables execute either synchronously or asynchronously, and the .forEach
from IxJS is essentially the same as RxJS's .subscribe
method when paired with the almost-identical from
creator function. The only other difference is IxJS's .forEach
method is optional because you could use the imperative for-of
instead.
似乎有两个库无缘无故,因为RxJS的from
创建者函数可以将Iterables转换为Observables.
It seems like there are two libraries for no reason because RxJS's from
creator function can convert Iterables to Observables.
在我看来,它不是真正的IxJS和RxJS,而是Iterables和Observables.它们有什么不同?什么时候可以使用另一个?
From my perspective, it's not really IxJS and RxJS, it's Iterables and Observables. How are they different and when would you use one over the other?
推荐答案
tl; dr
RxJS会在值到达后立即对其进行处理.这是一个推送系统.
IxJS指定何时传递下一个值.这是一个拉系统.
IxJS specifies when to pass in the next value. It's a pull system.
IxJS
如果想要基于拉的模型,例如在处理背压时,可能会有所帮助.
IxJS
may be helpful if want to have pull-based model, for example, when dealing with backpressure.
您可以在文档中看到
换句话说:
- 如果您的生产者(通常是用户)比数据处理的速度慢(这在前端很常见),请使用
RxJS
. - 如果生产者(通常是System)比处理数据快得多(对于后端来说更常见),请使用
IxJS
.
- Use
RxJS
if your producer (usually User) is slower that processing of data (this is common for frontend). - Use
IxJS
if your producer (usually System) is much faster than you can process data (more common for the backend).
要了解这意味着什么,请考虑以下示例:
To understand what this means, consider the following example:
如果使用RxJS编写,则类似:
If you write it with RxJS, something like:
readFileByLineObservable('path/to/file')
.pipe(
doSomeHeavyTransformation(),
)
.subscribe()
然后,readFileByLineObservable
将尝试尽快将1TB的整个文件推"到RAM中.仅在发生这种情况之后,您才开始执行doSomeHeavyTransformation
.此问题称为背压.
Then readFileByLineObservable
will try to "push" the entire file of 1TB into RAM as soon as possible. Only after this occurs, you will start to do doSomeHeavyTransformation
. This problem is called backpressure.
相反,IxJS
仅在处理前一行后才尝试拉"每个换行.这是这种情况下的最佳处理方法.
In contrast, IxJS
will try to "pull" each newline only after previous line was processed. That's the optimal processing method in this case.
区别在于RxJS的.subscribe
设置侦听器的方式,而IxJS的.forEach
告诉其迭代器何时提供下一个值(仅在处理完第一个值之后.它与RxJS的相似但不相同) concatMap
和concatAll
运算符.
The difference is how RxJS's .subscribe
sets up a listener whereas IxJS's .forEach
tells its iterator when to give the next value (only after its done processing the first one. It's similar to, but not the same as, RxJS's concatMap
and concatAll
operators.
这篇关于RxJS和IxJS之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!