如何在Java中正确使用Apollo客户端的RxJava2库进行同步调用?

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

RxJava2 可用于 Apollo GraphQL JVM. 但我能想出如何正确使用它。我试着同步使用它,但问题是我在.map(value -> Optional.of(value.data())行得到错误。

/**
 * This method is supposed to send an Apollo Call, map the data of the Responses into Optionals and 
 * give back the Optional<Data> object.
 * @param <T>: the build query
 * @param <V>: the expected data structure
 *
*/
    public static <T extends com.apollographql.apollo.api.Query> Optional<Data> execute(
            T operation) {
        ApolloClient client = new CommonClient().getClient();
        ApolloCall<Data> apolloCall = client.query(operation);
        return Rx2Apollo.from(apolloCall)
                .map(value -> Optional.of(value.data()))
                .onErrorReturn(o ->  {
                  logger.error(o.getMessage());
                  return Optional.empty();
                })
                .blockingFirst();
    }

但问题是我在.map(value -> Optional.of(value.data()))行得到一个错误。错误是

java.util.Optional cannot be cast tocom.example.graphql.client.KundeQuery$Data.

那么,我到底做错了什么?或者至少有一种更简单的方法来同步处理Apollo GraphQL JVM客户端中的数据吗?

java spring-boot graphql rx-java2 apollo-client
1个回答
0
投票

我已经明白了。传入的数据结构是Response&gt;而不是&gt;。所以它无法读取它。解决方案可能是这样的。

public static <T extends com.apollographql.apollo.api.Query> Optional<Data> execute(T operation) {

    ApolloClient client = new CommonClient().getClient();
    ApolloCall<Optional<Data>> apolloCall = client.query(operation);

    return Rx2Apollo.from(apolloCall)
            .map(IncomingResponse::extracted)
            .onErrorReturn(o -> {
                logger.error(o.getMessage());
                return Optional.empty();
                })
            .blockingFirst();
}

private static Optional<Data> extracted(Response<Optional<Data>> value) {
    Optional<Data> result = value.data();
    return result; //Optional.of(localData);
}
© www.soinside.com 2019 - 2024. All rights reserved.