可观察对象相对于异步迭代器的优势

Advantages of observables to async interators

Observables 异步推送它们的数据,我感兴趣的是它们与拉取数据的对应对象(即异步可迭代对象)相比如何。

我遇到了这个 ReactiveX article

You can think of the Observable class as a “push” equivalent to Iterable, which is a “pull.” With an Iterable, the consumer pulls values from the producer and the thread blocks until those values arrive. By contrast, with an Observable the producer pushes values to the consumer whenever values are available. This approach is more flexible, because values can arrive synchronously or asynchronously.

特别是,我不明白最后引用的那一行。有人可以解释一下推的所谓优势吗?

Observables push their data through asynchronously

这是不正确的。它可以是同步的和异步的


post 中的引用指向 [Symbol.iterator],而不是新的 ES2015 [Symbol.asyncIterator]


This approach is more flexible, because values can arrive synchronously or asynchronously

因此,与 [Symbol.iterator] 相比,Observable 不会阻塞线程,也可以在同步和异步源上工作。


将 Observable 与 [Symbol.asyncIterator] 进行比较,来自 MDN 的重要引述:

There are currently no built-in JavaScript objects that have the [Symbol.asyncIterator] key set by default

所以 [Symbol.asyncIterator]Observable:

[Symbol.asyncIterator]:

const myAsyncIterable = new Object();
myAsyncIterable[Symbol.asyncIterator] = async function*() {
    yield "hello";
    yield "async";
    yield "iteration!";
};

(async () => {
    for await (const x of myAsyncIterable) {
        console.log(x);
        // expected output:
        //    "hello"
        //    "async"
        //    "iteration!"
    }
})();

可观察:

of('hello', 'async', 'iteration!').subscribe(console.log)

使用 Rx,您的编程范式发生了变化,您的数据通过 Streams 流动。

它改变了操作数据的方式,从 "pulling" 数组中的值并处理它们,到期望数据在您的过程中 "pushed"。 Rx 允许您以不同的方式使用流过滤、映射、去抖动数据,如果需要,还可以异步映射数据。

今年我改变了使用 Rx 编码的方式,我爱上了它!