Streams vs Observables

302 views Asked by At

This might be a dumb question to ask here.

I just wanted to know the difference between the Streams and Observables in JavaScript (or in any other language). I know that both of them are push data models i.e., responds on receiving data rather than pulling data. It would be great if someone could provide more differences between these two.

1

There are 1 answers

0
Alexei Kaigorodov On

Streams are usually pull-based. At the example below, foreach() (last method in the pipeline) starts the pipeline execution and pulls data from the source list.

    List<Integer> lst = Arrays.asList(1,2,3);
    lst.stream()
            .filter(k -> k > 1)
            .forEach(k->
                    System.out.println(k)
            );

On the other hand, Observables (and Publishers) are push-based. They start execution by themselves and push information into their subscribers. So subscribers must implement some interface which contains appropriate method which accepts the next value. Typically this method is named "update", "onNext", "post", "send", etc.

Push-based approach can cause troubles, when publisher (producer) works faster than subscriber (consumer). In such cases, reactive streams can help, where consumer may control the speed of producer, thus changing the transfer policy to pull-based.