如何在 Android 上使用 GraphQL 和 Retrofit? [英] How to use GraphQL with Retrofit on Android?

查看:35
本文介绍了如何在 Android 上使用 GraphQL 和 Retrofit?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 GraphQL 的新手,但我已经使用 Retrofit 一段时间了,它易于使用且速度快.在传递数据的方式方面,GraphQL 与 rest api 有很大不同.关于在 Android 上使用 GraphQL 的教程真的不多,我只能找到这个视频 (https://www.youtube.com/watch?v=P0uJHI7GjIc&t=1s) 但里面没有真正的代码.

I'm new to GraphQL but I have been using Retrofit for a while now and its easy to use and fast. GraphQL is much different than rest apis in terms of how you pass data. There really are not too many tutorials out there on using GraphQL with Android, I was only able to find this video (https://www.youtube.com/watch?v=P0uJHI7GjIc&t=1s) but there is no real code in there.

在我当前的改造调用代码中,我设置了一个端点:

In my current code for retrofit calls I have an endpoint I set like so:

final RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint(endPoint)
                .build();
        T service = restAdapter.create(clazz);

然后我调用这样的休息服务:

Then I call a rest service like this:

@GET("/users/{login}")
    Observable<Github> getUser(@Path("login") String login);

现在使用 GraphQL,您只有一个基本 url,没有服务路径.此外,如果您像 userId=1 一样查询,那么您必须使用 Body 参数作为 Post 发送:

Now with GraphQL you only have a base url and no service path. Also if you are querying like userId=1 then you have to send as Post with Body parameters:

operationName: arbitrary name ,
query: "{users(userid:$userId){username}}, 
variables: "{"userId":1}"

我只是不确定这如何转化为 Retrofit

I'm just not sure how this translates to Retrofit

推荐答案

Building Queries &解析 GraphQL 的响应并不简单.如果您在宠物项目中使用它,我建议您开始探索 Apollo.此客户端正在认真开发中,但您已经可以查看并使用它了.

Building Queries & Parsing responses for GraphQL is not straightforward. If you are using this on pet-projects, i recommend to start exploring Apollo. This client is under serious development but you can already have a look and play with it.

https://github.com/apollographql/apollo-android

到目前为止,我很享受与 Apollo 的合作,他们的路线图上有一些不错的功能:RxJava 集成、改造、订阅和对 AutoValue 的支持

I enjoyed working with Apollo so far, and there are nice features on their roadmap: RxJava Integration, Retrofit, Subscriptions and support for AutoValue

这篇关于如何在 Android 上使用 GraphQL 和 Retrofit?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆