RxJava timeout conditionally

23 Views Asked by At

RxJava observable need to apply the timeout based on some condition. If the condition is false, it should not apply any timeout.

Observable<String> obs2 = Observable
        .fromCallable(longTask)
        .timeout(100, TimeUnit.MILLISECONDS) //Want to do this based on a condition
        .onErrorResumeNext(new Func1<Throwable, Observable>() {
            @Override
            public Observable call(Throwable throwable) {
                System.out.println("Fallback task triggered");
                return null;
            }
    });
1

There are 1 best solutions below

0
akarnokd On

Just split up the definition and apply the timeout conditionally:

Observable<String> obs = Observable.fromCallable(longTask);
if (condition) {
   obs = obs.timeout(100, TimeUnit.MILLISECONDS);
}
return obs.onErrorResumeNext(err -> ...);