我有一个返回Observable
的网络调用,我有另一个网络调用,它不是rx,它取决于第一个Observable
,我需要以某种方式将它全部转换为Rx。
Observable<Response> responseObservable = apiclient.executeRequest(request);
执行后我需要做另一个不返回Observable
的http调用:
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调用渲染响应?
答案 0 :(得分:2)
您可以使用Observable
(RxJava1)或Observable.fromEmitter
(RxJava2)和Observable.create
将非同步非rx调用包装到Observable.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(...)