2017-10-05 36 views
0

我是RxJava的新手,我需要以异步方式使用Observable功能。在RxJava中超时

我还需要使用超时:在我的例子中,我希望每个进程在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已经睡了3秒钟。

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

谢谢你帮助我。

回答

2

根据the docstimeout操作者将:

镜源观察的,但如果时间过去而没有任何发射项的特定时期

因此,超时是发出错误通知如果延迟发生发生事件,但您已延迟事件消耗事件,并且不会导致超时。

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

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 
+0

感谢你的帮助,效果很好! – tlebras