Reputation: 6196
Observables push their data through asynchronously, and I'm interested in how they compare to their counterpart which pulls data, namely an async iterable.
I came across this 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.
Particularly, I don't understand that last quoted line. Could someone please explain that supposed advantage of pushing?
Upvotes: 4
Views: 158
Reputation: 2136
With Rx your programming paradigm changes, and your data flows via Streams.
It changes the way to manipulate data, from "pulling" values from arrays and processing them, to expect data to be "pushed" through your process. Rx allows you to play with the stream filtering, mapping, debouncing your data in different ways, and also mapping your data asynchronously if you need to.
This year I've changed the way I code using Rx, and I'm loving it!
Upvotes: 1
Reputation: 11000
Observables push their data through asynchronously
Thats not correct. It can be both - synchronous and asynchronous
[Symbol.iterator]
, not the new ES2015 [Symbol.asyncIterator]
.
This approach is more flexible, because values can arrive synchronously or asynchronously
So compared to to [Symbol.iterator]
, Observable does not block the thread and also can work on both - synchronous and asynchronous sources.
Comparing Observable to [Symbol.asyncIterator]
, one important quote from MDN:
There are currently no built-in JavaScript objects that have the [Symbol.asyncIterator] key set by default
So [Symbol.asyncIterator]
vs 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!"
}
})();
Observable:
of('hello', 'async', 'iteration!').subscribe(console.log)
Upvotes: 1