避免在RxJava中进行阻塞

时间:2018-02-06 06:30:48

标签: java rx-java observable

我发现下面的代码(为了简洁而修改),这是有缺陷的,并且据我所知有缺陷。

  1. 使用toBlocking(),一般不推荐使用,并且已在反应式上下文中使用
  2. 返回single();所以只要它从流中获得单个项目,它就会终止它,忽略其他不可取的项目。
  3. 我相信我可以解决此问题,将single移至last?有人可以解释一下,我怎么能在这里删除toBlocking()的使用?

    observableList.map(incentiveDetailsList -> {
            List<SomeObject> list = mapThisList(incentiveDetailsList);
            return Observable.just(list)
                        .flatMap(Observable::from)
                        .flatMap(item -> {
                            Request request = createRequest(item);
                            String accountNumber = item.getAccountNumber();
                            return serviceThatReturnsObservable.load(request)
                                    .doOnError(onError -> {
                                        Observable.error(new Exception("some context"));
                                    })
                                    .map(response -> {
                                        handleError(response);
                                        return responseMap.put(accountNumber, buildResponse(response.getResponse()));
                                    });
                        })
                        .map(resp -> mapResponse(store, incentiveDetailsList, responseMap))
                        .toBlocking()
                        .single();
    })
    

1 个答案:

答案 0 :(得分:1)

您可以使用flatMap(或concatMap)替换map + toBlocking:

 observableList.flatMap(incentiveDetailsList -> {
    List<SomeObject> list = mapThisList(incentiveDetailsList);
    return Observable.from(list)
           .flatMap(item -> {
               Request request = createRequest(item);
               String accountNumber = item.getAccountNumber();
               return serviceThatReturnsObservable.load(request)
                   /* this has no effect:
                            .doOnError(onError -> {
                                Observable.error(new Exception("some context"));
                            })
                    */
                    .map(response -> {
                         handleError(response);
                         return responseMap.put(accountNumber, 
                            buildResponse(response.getResponse()));
                    });
            })
            .map(resp -> mapResponse(store, incentiveDetailsList, responseMap));
})