Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava2 Blocking Observable Timeout: How do I emit a result when timeout fires?

I have an Observable that emits events in the form of JSON strings. I want to subscribe to it blocking and get the first string. Not a problem.

But I would like to also have a timeout and emit a canned JSON string when the timeout fires.

Here is my existing code:

String jsonString = rxEvents.subscribe().toBlocking().first();
like image 877
EBarnett Avatar asked Aug 11 '17 22:08

EBarnett


1 Answers

Just use version of timeout that takes 3 parameters:

rxEvents
  .timeout(1, TimeUnit.SECONDS, Observable.just("fallback"))
  .toBlocking()
  .first()

Note that in your sample code subscribe is not needed.

like image 122
hgrey Avatar answered Sep 23 '22 10:09

hgrey