2017-02-14 51 views
4

我有一个网络调用,返回Observable,并且我有另一个网络调用,它不是rx,取决于第一个Observable,我需要以某种方式将其与Rx全部转换。如何调用取决于rx网络调用的非rx网络调用

Observable<Response> responseObservable = apiclient.executeRequest(request); 

执行我需要做的另一个HTTP调用不返回Observable后:

responseObservable.map(response - > execute the no rx network call using the response.id) 

noRxClient.getInformation(response.id, new Action1<Information>() { 
    @Override 
    public void call(Information information) { 
     //Need to return information with page response 
    } 
}); 

我需要调用此方法来呈现响应,那么后

renderResponse(response, information); 

如何我可以将非rx呼叫连接到rx,然后使用RxJava调用渲染响应?

回答

2

你可以用你的异步非RX调用到(RxJava2)Observable使用Observable.fromEmitter(RxJava1)或Observable.createObservable.fromCallable(非异步调用):

private Observable<Information> wrapGetInformation(String responseId) { 
    return Observable.create(emitter -> { 
     noRxClient.getInformation(responseId, new Action1<Information>() { 
      @Override 
      public void call(Information information) { 
       emitter.onNext(information); 
       emitter.onComplete(); 
       //also wrap exceptions into emitter.onError(Throwable) 
      } 
     }); 
    }); 
} 

private Observalbe<RenderedResponse> wrapRenderResponse(Response response, Information information) { 
    return Observable.fromCallable(() -> { 
     return renderResponse(response, information); 
     //exceptions automatically wrapped 
    }); 
} 

与结果相结合使用overloaded flatMap操作:

apiclient.executeRequest(request) 
    .flatMap(response -> wrapGetInformation(response.id), 
      (response, information) -> wrapRenderResponse(response, information)) 
    ) 
    //apply Schedulers 
    .subscribe(...) 
+0

如果wrapRenderResponse不返回任何内容会发生什么?它只是呈现回应。如何修改该代码? –