gpt4 book ai didi

java - RxJava 中的超时

转载 作者:行者123 更新时间:2023-12-02 23:43:01 29 4
gpt4 key购买 nike

我是 RxJava 新手,我需要以异步方式使用 Observable 功能。

我还需要使用超时:在我的示例中,我希望每个进程在 1 秒或更短的时间内结束。

这是我现在所做的:

public static void hello(String name) throws IOException {
Observable<String> obs2 = Observable.just(name).timeout(1000, TimeUnit.MILLISECONDS).subscribeOn(Schedulers.io());
obs2.subscribe(new Action1<String>() {
@Override
public void call(String s) {
if("CCCCC".equals(s)){
try {
Thread.sleep(3200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(s + " " + new Date() +" "+Thread.currentThread().getName());
}
});
}

public static void main(final String[] args) throws InterruptedException, IOException {
hello("AAAAA");
hello("CCCCC");
hello("BBBBBB");
System.in.read();
}

结果:

AAAAA Thu Oct 05 09:43:46 CEST 2017 RxIoScheduler-2
BBBBBB Thu Oct 05 09:43:46 CEST 2017 RxIoScheduler-4
CCCCC Thu Oct 05 09:43:49 CEST 2017 RxIoScheduler-3

我实际上期望从名为“RxIoScheduler-3”的线程中获得 TimeoutException,因为它已经 hibernate 了 3 秒。

我的代码和 RxJava 中的超时方法有什么问题?

谢谢你帮助我。

最佳答案

根据the docs timeout 运算符将:

mirror the source Observable, but issue an error notification if a particular period of time elapses without any emitted items

因此,如果发出事件存在延迟,但您在消耗事件中设置了延迟,并且不会导致超时,则认为发生了超时.

如果您修改代码以在发射期间暂停,则会发生超时。例如:

public static void hello(String name) throws IOException {
Observable<String> obs2 = Observable.fromCallable(() -> {
if ("CCCCC".equals(name)) {
// pause for 150ms before emitting "CCCCC"
try {
Thread.sleep(150);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return name;
}
).timeout(100, MILLISECONDS) // timeout if there is a pause in emission of more than 100ms
.subscribeOn(Schedulers.io());

obs2.subscribe(s -> System.out.println(s + " " + new Date() + " " + Thread.currentThread().getName()),
throwable -> System.err.println(throwable.getClass().getSimpleName() + " " + new Date() + " " + Thread.currentThread().getName()));
}

使用上述形式的hello(),您将得到写入控制台的以下输出:

AAAAA Thu Oct 05 10:10:33 IST 2017 RxIoScheduler-2
BBBBBB Thu Oct 05 10:10:33 IST 2017 RxIoScheduler-4
TimeoutException Thu Oct 05 10:10:33 IST 2017 RxComputationScheduler-1

关于java - RxJava 中的超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46580869/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com