RxJava:如果第一次调用成功,如何进行第二次api调用,然后创建一个组合响应。

问题描述 投票:0回答:1

这就是我想做的。

  1. 调用第一个休息API
  2. 如果第一次成功,则调用第二次,其余的API
  3. 如果两者都成功 -> 创建一个聚合响应。

我在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();
    }
}
rx-java2 micronaut
1个回答
1
投票

这应该是最简单的

public Single<AggregatedResponse> login(String data) {
    return firstRestApi.call(data)
             .flatMap((firstResponse) -> secondRestApi.call().map((secondResponse) -> {
                 return Pair.create(firstResponse, secondResponse);
             })
             .map((pair) -> {
                 return convertResponse(pair.getFirst(), pair.getSecond());
             });
}

在这种情况下,你不再需要 zipWith. 错误就像往常一样进入错误流。

© www.soinside.com 2019 - 2024. All rights reserved.