2017-01-28 60 views

回答

-1

下面是使用RxJava Observables的示例工作代碼,該代碼打印來自一組線程的最快響應線程的結果。

public static void main(String[] args) { 
      // Create a slow thread which spans 5 secs 
      Callable<String> task1 = new Callable<String>() { 

        @Override 
        public String call() throws Exception { 
          Thread.sleep(5000); 
          return "task1"; 
        } 
      }; 
      // Create a faster thread which spans 1 secs 
      Callable<String> task2 = new Callable<String>() { 

        @Override 
        public String call() throws Exception { 
          Thread.sleep(1000); 
          return "task2"; 
        } 
      }; 
      List<Callable<String>> tasks = new ArrayList<>(); 
      tasks.add(task1); 
      tasks.add(task2); 

      String result = null; 
      try { 
        result = Observable.from(tasks) 
            .subscribeOn(Schedulers.computation()) 
            .flatMap(eachTask -> Observable.fromCallable(eachTask) 
                .subscribeOn(Schedulers.io()) 
                .doOnNext(e -> System.out.println("Executing your action on "+Thread.currentThread().getName())) 
                .doOnError(e -> System.out.println("Failed reason for : "+Thread.currentThread().getName()+" with error "+e.getMessage())) 
                ) 
            .toBlocking() 
            .first(); 

      } catch (Exception e) { 
        System.out.println(e.getMessage()); 
      } 
      System.out.println("result--->"+result); 
} 
+0

不好的建議,這等待所有的人完成,然後拿第一個。 –

+0

@DanieleSegato nope,如果你可以執行代碼,你會發現它不會等待它們全部完成。它會選擇BlockingObservable返回的FIRST項目。 – Sabarish

+0

無論如何,請求調用merge + take(1)或合併+ first() –

3

如果我理解你的權利,你需要的東西是這樣的:

taskSource 
    .flatMap(task -> // for each task 
     Observable.merge(
      // submit same task to multiple services 
      service1.submit(task), 
      service2.submit(task), 
      ..., 
      serviceN.submit(task) 
      ) 
      .take(1)) // take first response; discard others 
    ... // continue processing result of the task 
    .subscribe(...) 
2

您希望Observable.amb操作。它具有與不止一種排放的Observables一起工作的好處。

+0

謝謝你會檢查出來。 – Sabarish

相關問題