如何使用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. servelet 实现Post接口访问

    先上代码: package com.jovtec.galaxy.mailbox; import java.io.BufferedReader; import java.io.IOException; ...

  2. 读取本地文本写入list

    /** * 读取15151433862----123456文档 * @param f */ private static void findContent(File f){ String line = ...

  3. Java开发中POJO和JSON互转时如何忽略隐藏字段

    1. 前言 在Java开发中有时候某些敏感信息我们需要屏蔽掉,不能被消费这些数据的客户端知道.通常情况下我们会将其设置为null或者空字符 "",其实还有其它办法,如果你使用了Ja ...

  4. CF-1332 F. Independent Set

    F. Independent Set 题意 一颗 n 个节点的树,求出每个\(edge-induced~subgraph\)的独立集个数之和. \(edge-induced~subgraph\)含义是 ...

  5. 1155 Heap Paths

    题干前半略. Sample Input 1: 8 98 72 86 60 65 12 23 50   Sample Output 1: 98 86 23 98 86 12 98 72 65 98 72 ...

  6. P4755 Beautiful Pair (分治 + 主席树)

    题意:1e5的数组 计算有多少对 ai * aj <= max(ai ai+1...aj-1 aj) 题解:在处理这种涉及到区间极值的题时 好像是个套路分治 从级值中间分成两个区间 从区间短的那 ...

  7. Checkout Assistant CodeForces - 19B

    题意: 给你n个物品,每个物品有一个价格ci和一个支付时间ti,在这个ti时间内,你可以免费拿ti个物品.问你想要带走这n个物品最小需要多少钱 题解: 原本还想着贪心去写,但是好像贪心写不了,,,不属 ...

  8. Dubbo从入门到实践

    1 Dubbo出现的背景 随着互联网的发展,网站应用的规模不断扩大,常规的垂直应用架构已无法应对,分布式服务架构以及流动计算架构势在必行,亟需一个治理系统确保架构有条不紊的演进. 我们传统的网站结构为 ...

  9. While & For 循环

    While 循环 可以将 While 循环称为 "条件循环" While 循环语法 # 条件为 true 就执行循环体代码,条件变为 false 循环结束 while 条件 do ...

  10. hdu 4465 Candy (非原创)

    LazyChild is a lazy child who likes candy very much. Despite being very young, he has two large cand ...