2017-02-14 83 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不返回任何內容會發生什麼?它只是呈現迴應。如何修改該代碼? –