Search code examples
javascriptecmascript-6rxjsreactivex

Advantages of observables to async interators


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?


Solution

  • Observables push their data through asynchronously

    Thats not correct. It can be both - synchronous and asynchronous


    The quote in your post points to the [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)