【发布时间】:2020-06-02 20:02:33
【问题描述】:
这就是我想做的:
- 调用第一个休息 API
- 如果第一次成功调用秒休息API
- 如果两者都成功 -> 创建聚合响应
我在 Micronaut 中使用 RxJava2。
这是我所拥有的,但我不确定它是否正确。如果第一次或第二次 API 调用失败会怎样?
@Singleton
public class SomeService {
private final FirstRestApi firstRestApi;
private final SecondRestApi secondRestApi;
public SomeService(FirstRestApi firstRestApi, SecondRestApi secondRestApi) {
this.firstRestApi = firstRestApi;
this.secondRestApi = secondRestApi;
}
public Single<AggregatedResponse> login(String data) {
Single<FirstResponse> firstResponse = firstRestApi.call(data);
Single<SecondResponse> secondResponse = secondRestApi.call();
return firstResponse.zipWith(secondResponse, this::convertResponse);
}
private AggregatedResponse convertResponse(FirstResponse firstResponse, SecondResponse secondResponse) {
return AggregatedResponse
.builder()
.something1(firstResponse.getSomething1())
.something2(secondResponse.getSomething2())
.build();
}
}
【问题讨论】:
-
您的代码没问题,如果两个请求之一失败,zip 也会失败。另一方面,如果您想在第二次调用中使用第一次 api 调用的结果,那么您必须使用 concatMap 运算符。