【问题标题】:RxJava: how to do a second api call if first is successful and then create a combinded responseRxJava:如果第一次成功,如何进行第二次 api 调用然后创建组合响应
【发布时间】:2020-06-02 20:02:33
【问题描述】:

这就是我想做的:

  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();
    }
}

【问题讨论】:

  • 您的代码没问题,如果两个请求之一失败,zip 也会失败。另一方面,如果您想在第二次调用中使用第一次 api 调用的结果,那么您必须使用 concatMap 运算符。

标签: rx-java2 micronaut


【解决方案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。错误只是像往常一样进入错误流。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 2012-07-31
    • 2017-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多