[英]Setting a timeout until Observable's data completes
There is a rx.Observable.timeout
but it's per item and not for all data. 有一个
rx.Observable.timeout
但它是针对每个项目的,而不是针对所有数据的。 But I need a timeoutexception if data is not emitted within specific period of time. 但是,如果在特定时间段内未发出数据,则需要timeoutexception。
final Subscriber<Integer> sub = new Subscriber<Integer>() {
@Override
public void onNext(Integer num) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {}
System.out.println(num);
}
@Override
public void onCompleted() {
System.out.println("--------------- Done ---------------");
}
@Override
public void onError(Throwable e) {
//System.out.println("Error!!! + e");
}
};
Observable.range(1, 10000)
.map(x -> x * 10)
//.last()
.timeout(10, TimeUnit.SECONDS)
.doOnError( e -> {System.out.println("Errrorrr " + e);})
.subscribe(sub);
You could use takeUntil(Observable)
with timer()
mapped into an exception: 您可以将
takeUntil(Observable)
与timer()
映射到一个异常中:
source.takeUntil(
Observable.timer(10, TimeUnit.SECONDS)
.flatMap(ignored -> Observable.error(new TimeoutException()))
)
.subscribe(/* ... */);
Use two sources: one emitting your data, one throwing your timeout exception after a delay. 使用两种来源:一种来源发送数据,一种来源在延迟后引发超时异常。 Merge the two:
合并两个:
Observable timeoutObservable = Observable.error(new TimeoutException())
.delay(10, TimeUnit.SECONDS, true);
return Observable.merge(dataObservable, timoutObservable);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.