Let's go back to our Observable temperature sensor. It's emitting the current room temperature every second. Honestly, we don't think the temperature will change so rapidly, and we could use a less stressful emitting interval. Appending sample()
to the Observable source, we will create a new Observable sequence that will emit the most recent item emitted by the Observable source in a decided time interval:
Observable<Integer> sensor = […] sensor.sample(30, TimeUnit.SECONDS) .subscribe(new Observer<Integer>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(Integer currentTemperature) { updateDisplay(currentTemperature); } });
The Observable in the example will observe the Observable source temperature and emit the last emitted temperature value every 30
seconds. Obviously, sample()
supports a full set of TimeUnit
values: seconds, milliseconds, day, minutes, and so on.
The next figure shows how an Observable interval emitting letters will sample an Observable emitting numbers. The Observable result will emit the last number of every emitted letter: 1, 4, 5.
If we want the first item emitted in the time interval instead of the last item, we can use throttleFirst()
instead.
3.149.241.250