这是我想要做的......
执行一系列任务。每个任务需要在x秒内完成。 如果没有完成,请记录超时并继续处理下一次发射。
public static void main(String[] args) {
Observable<String> source = Observable.create(emitter -> {
emitter.onNext(task(0, "A"));
emitter.onNext(task(2, "B")); // this one times out
emitter.onNext(task(0, "C"));
emitter.onNext(task(0, "D"));
emitter.onComplete();
});
source.subscribeOn(Schedulers.computation())
.timeout(1, TimeUnit.SECONDS, Observable.just("timeout"))
.blockingSubscribe(s -> System.out.println("RECEIVED: " + s));
}
private static String task(int i, String string) {
try {
TimeUnit.SECONDS.sleep(i);
}
catch (InterruptedException e) {
}
return string;
}
实际结果
收到:A RECEIVED:超时
预期结果
收到:A 收到:超时
收到:C
收到:D
基本上我不希望排放在超时时终止。
答案 0 :(得分:2)
您可以推迟执行任务并分别应用timeout
:
Observable<String> source = Observable.create(
(ObservableEmitter<Callable<String>> emitter) -> {
emitter.onNext(() -> task(0, "A"));
emitter.onNext(() -> task(2, "B")); // this one times out
emitter.onNext(() -> task(0, "C"));
emitter.onNext(() -> task(0, "D"));
emitter.onComplete();
})
.concatMap(call ->
Observable.fromCallable(call)
.subscribeOn(Schedulers.computation())
.timeout(1, TimeUnit.SECONDS, Observable.just("timeout"))
);
source
.blockingSubscribe(s -> System.out.println("RECEIVED: " + s));