Let's suppose we are working in a very time-sensitive environment. Our temperature sensor is emitting a value every second. We want to be absolutely sure we get at least one value every two seconds. We can use the timeout()
function to mirror the source Observable sequence and emit an error if we don't get a value for the time interval we decided. We can consider timeout()
as a time-constrained copy of our Observable. It mirrors the original Observable and fires onError()
if the Observable doesn't emit values in the decided time interval:
Subscription subscription = getCurrentTemperature() .timeout(2, TimeUnit.SECONDS) .subscribe(new Observer<Integer>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { Log.d("RXJAVA", "You should go check the sensor, dude"); } @Override public void onNext(Integer temperature) { updateDisplay(temperature); } });
Like sample()
, timeout()
uses the TimeUnit
object to specify the time interval.
The next figure shows how the Observable will trigger onError()
the moment the Observable violates the timeout constraint: the last item won't be emitted because it arrives after the timeout.
18.119.106.135