如何使用GraphQL Client: Apollo Android

一个Android app, 如何使用GraphQL.

本文以最流行的Apollo Android为例来说明.

添加依赖

首先, 添加依赖:

https://www.apollographql.com/docs/android/essentials/get-started-kotlin/

注意在android block里这两个东东都要加上:

    compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}

下载Schema

然后, 下载schema.

可以跑一个introspection query来获取.

Apollo的Gradle插件贴心地提供了这个功能, 用downloadApolloSchema这个task就可以.

只需要提供server的endpoint和存储schema.json文件的位置:

./gradlew downloadApolloSchema \
--endpoint="https://your.domain/graphql/endpoint" \
--schema="src/main/graphql/com/example/schema.json"

如果是需要认证的endpoint:

./gradlew downloadApolloSchema \
--endpoint="https://your.domain/graphql/endpoint" \
--schema="app/src/main/graphql/com/example" \
--header="Authorization: Bearer $TOKEN"

这里我曾经有过一个疑问, 我这个TOKEN属于哪个用户的要紧吗? -> 不要紧.

注意: 此时用的Token只是为了获取schema, 实际请求的时候还是要带具体当时的token.

添加.graphql文件, build生成代码

找Playground测试, 比如GitHub GraphQL API可以用Explorer测试: https://developer.github.com/v4/explorer/

然后把这个.graphql文件写在schema文件旁边.

比如:

CurrentUser.graphql中:

query CurrentUser {
viewer {
login
avatarUrl
name
}
}

Build, 生成代码.

生成代码在生成文件的路径.

比如CurrentUser.graphql里面是一个query, 就生成了CurrentUserQuery文件.

进行请求调用 (协程版本)

采用协程版本的代码, 在ViewModel的scope里面:

viewModelScope.launch {
val response = try {
apolloClient.query(CurrentUserQuery()).toDeferred().await()
} catch (e: ApolloException) {
// handle protocol errors
return@launch
} val viewer = response.data?.viewer
if (viewer == null || response.hasErrors()) {
// handle application errors
return@launch
}
_user.postValue(viewer) println("Launch site: ${viewer.login}")
}

其中toDeferred()方法将结果转换为Deferred<T>, 是Job的一个子类, await()方法返回协程的结果.

Apollo Client Android的协程支持

添加了这个依赖之后:

implementation("com.apollographql.apollo:apollo-coroutines-support:2.2.3")

会有一个辅助类, 里面目前是5个扩展方法:

  • Converts an [ApolloCall] to an [Flow]
  • Converts an [ApolloQueryWatcher] to an [Flow].
  • Converts an [ApolloCall] to an [Deferred].
  • Converts an [ApolloSubscriptionCall] to an [Flow].
  • Converts an [ApolloPrefetch] to [Job].

认证请求

关于认证的请求:

https://www.apollographql.com/docs/android/tutorial/10-authenticate-your-queries/

同样也是加interceptor来解决:

return ApolloClient.builder()
.serverUrl("https://api.github.com/graphql")
.okHttpClient(
OkHttpClient.Builder()
.addInterceptor(authInterceptor)
.build()
)
.build()

其中authInterceptor和用Retrofit时候的一样.

class AuthInterceptor constructor(private val preferencesUtils: PreferencesUtils) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val userToken = preferencesUtils.userToken
val newBuilder = chain.request().newBuilder()
if (userToken != null && userToken.isNotEmpty()) {
newBuilder.addHeader("Authorization", "token $userToken")
}
newBuilder.addHeader("Accept", "application/vnd.github.v3+json")
val request = newBuilder.build()
return chain.proceed(request)
}
}

参考

如何使用GraphQL Client: Apollo Android的更多相关文章

  1. grandstack 基于graphql&&react&& apollo&& neo4j 的全栈开发工具

    grandstack是一个基于graphql&&react&& apollo&& neo4j 的全栈开发工具. 有篇关于graphql 的5个常见问题的 ...

  2. urql 高度可自定义&&多功能的react graphql client

    urql 是一个很不错的graphql client,使用简单,功能强大,通过exchanges 实现了完整的自定义特性 通过urql 的exchanges 我们可以实现灵活的cache策略 参考资料 ...

  3. GraphQL + React Apollo + React Hook + Express + Mongodb 大型前后端分离项目实战之后端(19 个视频)

    GraphQL + React Apollo + React Hook + Express + Mongodb 大型前后端分离项目实战之后端(19 个视频) GraphQL + React Apoll ...

  4. GraphQL + React Apollo + React Hook 大型项目实战(32 个视频)

    GraphQL + React Apollo + React Hook 大型项目实战(32 个视频) GraphQL + React Apollo + React Hook 大型项目实战 #1 介绍「 ...

  5. 使用graphql和apollo client构建react web应用

    graphql是一种用于 API 的查询语言(摘自官网). 我们为什么要用graphql? 相信大家在开发web应用的时候常常会遇到以下这些问题:后端更新了接口却没有通知前端,从而导致各种报错:后端修 ...

  6. An HTTP & HTTP/2 client for Android and Java applications OkHttp

    HTTP is the way modern applications network. It’s how we exchange data & media. Doing HTTP effic ...

  7. Android 开发技术周报 Issue#277

    新闻 Android 11界面再调整:加入快速截屏.多任务向国产ROM看齐 最新版Android 11推送 谷歌Pixel 5被曝光:支持反向充电 4月Android系统版本分布:8.0 Oreo最主

  8. Android简单的聊天室开发(client与server沟通)

    请尊重他人的劳动成果.转载请注明出处:Android开发之简单的聊天室(client与server进行通信) 1. 预备知识:Tcp/IP协议与Socket TCP/IP 是Transmission ...

  9. Delphi revelations #1 – kbmMW Smart client on NextGen (Android) – Scope problems

    Delphi 启示 #1 – kbmMW Smart client on NextGen (Android) – 作用域问题 以更高级的方式使用kbmMW smart client,在Android设 ...

随机推荐

  1. cassandra权威指南读书笔记--读写数据

    写cassandra除了轻量级事务,不支持别的事务.cassandra是追加写,写的速度非常快.cassandra还有hint日志,这个数据库总是可写的,而且单个列的写操作是原子的.hint并不是一定 ...

  2. 漫画 | CPU战争40年,真正的王者终于现身!

    上个世纪70年代,内存又慢又贵, 程序员得想尽一切办法节省内存. 那个时代的编译器也比较差劲 所以,70年代的程序员几乎都写得一手好汇编. 为了帮助程序员写好汇编,这个时候的CPU也有意把指令集做了增 ...

  3. Best Reward && Girls' research

    After an uphill battle, General Li won a great victory. Now the head of state decide to reward him w ...

  4. leetcode8 字符串转换整数

    <cctype> isdigit(char) 问题:在做乘法,加法前,先判断是否溢出 &&优先级大于== 然后教训: 考虑情况不周.比如3.14这样 然后解决办法 多自己搞 ...

  5. Git使用出现Automatic merge failed; fix conflicts and then commit the result.解决方法

    产生原因 首先这个问题产生的原因是因为你git pull 的时候会分为两步,第一步先从远程服务器上拉下代码,第二步进行merge,但是merge时候失败了就会产生上述问题. 解决方法: 丢弃本地提交, ...

  6. Docker项目demo

     Docker数据持久化 4.1 Volume (1)创建mysql数据库的container (2)查看volume (3)具体查看该volume docker volume inspect 485 ...

  7. Commons Collections2分析

    0x01.POC分析 //创建一个CtClass对象的容器 ClassPool classPool=ClassPool.getDefault(); //添加AbstractTranslet的搜索路径 ...

  8. 渗透技巧——如何逃逸Linux的受限制shell执行任意命令

    导语:本文介绍了如何在受限制的shell中执行任意命令,实现交互.其相应的利用场景是说当我们通过一些手段拿到当前Linux机器的shell时,由于当前shell的限制,很多命令不能执行,导致后续的渗透 ...

  9. 白日梦的ES笔记三:万字长文 Elasticsearch基础概念统一扫盲

    目录 一.导读 二.彩蛋福利:账号借用 三.ES的Index.Shard及扩容机制 四.ES支持的核心数据类型 4.1.数字类型 4.2.日期类型 4.3.boolean类型 4.4.二进制类型 4. ...

  10. TypeScript keyof typeof All In one

    TypeScript keyof typeof All In one keyof typeof refs https://www.typescriptlang.org/docs/handbook/re ...