How to combine multiple RxJava chains non-blocking in error case

后端 未结 5 1447
旧巷少年郎
旧巷少年郎 2020-12-15 10:19

My requirements:

  • N Retrofit calls in parallel
  • Wait for all calls to finish (success or failure)
  • If k (0<= k < N) calls fail, they sho
5条回答
  •  时光取名叫无心
    2020-12-15 11:11

    I think in your use case Zip operator it´s more suitable

    Here you can see running in the main thread, but also it´s possible make it run every one of them in another thread if you use observerOn

    /**
     * Since every observable into the zip is created to subscribeOn a different thread, it´s means all of them will run in parallel.
     * By default Rx is not async, only if you explicitly use subscribeOn.
      */
    @Test
    public void testAsyncZip() {
        scheduler = Schedulers.newThread();
        scheduler1 = Schedulers.newThread();
        scheduler2 = Schedulers.newThread();
        long start = System.currentTimeMillis();
        Observable.zip(obAsyncString(), obAsyncString1(), obAsyncString2(), (s, s2, s3) -> s.concat(s2)
                                                                                            .concat(s3))
                  .subscribe(result -> showResult("Async in:", start, result));
    }
    
    
    
    private Observable obAsyncString() {
        return Observable.just("")
                         .observeOn(scheduler)
                         .doOnNext(val -> {
                             System.out.println("Thread " + Thread.currentThread()
                                                                  .getName());
                         })
                         .map(val -> "Hello");
    }
    
    private Observable obAsyncString1() {
        return Observable.just("")
                         .observeOn(scheduler1)
                         .doOnNext(val -> {
                             System.out.println("Thread " + Thread.currentThread()
                                                                  .getName());
                         })
                         .map(val -> " World");
    }
    
    private Observable obAsyncString2() {
        return Observable.just("")
                         .observeOn(scheduler2)
                         .doOnNext(val -> {
                             System.out.println("Thread " + Thread.currentThread()
                                                                  .getName());
                         })
                         .map(val -> "!");
    }
    

    You can see more examples here https://github.com/politrons/reactive

提交回复
热议问题