0
votes

Does Observable caches emitted items? I have two tests that lead me to different conclusions:

From the test #1 I make an conclusion that it does:

Test #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:

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:

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:

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

1 Answers

1
votes

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.