简体   繁体   English

可观察到的缓存发出的项目还是没有?

[英]Observable caches emitted items or does not?

Does Observable caches emitted items? Observable缓存发出的项目吗? I have two tests that lead me to different conclusions: 我有两项测试使我得出不同的结论:

From the test #1 I make an conclusion that it does: 从测试#1中,我得出结论:

Test #1: 测试#1:

Observable<Long> clock = Observable
    .interval(1000, TimeUnit.MILLISECONDS)
    .take(10)
    .map(i -> i++);

//subscribefor the first time
clock.subscribe(i -> System.out.println("a: " + i)); 

//subscribe with 2.5 seconds delay
Executors.newScheduledThreadPool(1).schedule(
    () -> clock.subscribe(i -> System.out.println("  b: " + i)),
    2500,
    TimeUnit.MILLISECONDS
);

Output #1: 输出#1:

a: 0
a: 1
a: 2
  b: 0
a: 3
  b: 1

But the second test shows that we get different values for two observers: 但是第二项测试表明,对于两个观察者,我们得到了不同的值:

Test #2: 测试2:

Observable<Integer> observable  = Observable
                .range(1, 1000000)
                .sample(7, TimeUnit.MILLISECONDS);
observable.subscribe(i -> System.out.println("Subscriber #1:" + i));
observable.subscribe(i -> System.out.println("Subscriber #2:" + i)); 

Output #2: 输出#2:

Subscriber #1:72745
Subscriber #1:196390
Subscriber #1:678171
Subscriber #2:336533
Subscriber #2:735521

There exist two kinds of Observables: hot and cold. 存在两种可观测值:热和冷。 Cold observables tend to generate the same sequence to its Observers unless you have external effects, such as a timer based action, associated with it. 除非您具有外部影响(例如基于计时器的操作),否则冷的可观察对象往往会与其观察者生成相同的序列。

In the first example, you get the same sequence twice because there are no external effects other than timer ticks you get one by one. 在第一个示例中,您获得两次相同的序列,因为除了定时器滴答之外,没有其他外部影响,您得到的是一个一个。 In the second example, you sample a fast source and sampling with time has a non-deterministic effect: each nanosecond counts so even the slightest imprecision leads to different value reported. 在第二个示例中,您对快速源进行采样,并且随时间采样具有不确定性:每个纳秒都会计数,因此即使是最小的不精确度也会导致报告的值不同。

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

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