简体   繁体   English

流与可观测值

[英]Streams vs Observables

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). 我只是想知道JavaScript(或任何其他语言)中的Streams和Observables之间的区别。 I know that both of them are push data models ie, responds on receiving data rather than pulling data. 我知道它们都是推数据模型,即响应接收数据而不是拉数据。 It would be great if someone could provide more differences between these two. 如果有人可以在这两者之间提供更多差异,那就太好了。

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. 在下面的示例中, foreach() (管道中的最后一个方法)启动管道执行并从源列表中提取数据。

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

On the other hand, Observable s (and Publisher s) are push-based. 另一方面, Observable (和Publisher )是基于推送的。 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. 通常,此方法名为“更新”,“ onNext”,“发布”,“发送”等。

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. 在这种情况下, reactive streams可以提供帮助,在此情况下,消费者可以控制生产者的速度,从而将传输策略更改为基于拉动的传输策略。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM