2017-10-05 37 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