4

我有一个返回 的网络调用,Observable我还有另一个网络调用,它不是依赖于第一个的 rx,Observable我需要以某种方式将其全部转换为 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 全部调用渲染响应?

4

1 回答 1

2

您可以将异步非 rx 调用包装到Observable使用Observable.fromEmitter(RxJava1) 或Observable.create(RxJava2) 和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
    });
}

并使用重载的 flatMap运算符组合结果:

apiclient.executeRequest(request)
    .flatMap(response -> wrapGetInformation(response.id), 
            (response, information) -> wrapRenderResponse(response, information))
    )
    //apply Schedulers
    .subscribe(...)
于 2017-02-15T00:35:09.587 回答