如何使用GraphQL Client: Apollo Android
如何使用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的更多相关文章
- grandstack 基于graphql&&react&& apollo&& neo4j 的全栈开发工具
grandstack是一个基于graphql&&react&& apollo&& neo4j 的全栈开发工具. 有篇关于graphql 的5个常见问题的 ...
- urql 高度可自定义&&多功能的react graphql client
urql 是一个很不错的graphql client,使用简单,功能强大,通过exchanges 实现了完整的自定义特性 通过urql 的exchanges 我们可以实现灵活的cache策略 参考资料 ...
- GraphQL + React Apollo + React Hook + Express + Mongodb 大型前后端分离项目实战之后端(19 个视频)
GraphQL + React Apollo + React Hook + Express + Mongodb 大型前后端分离项目实战之后端(19 个视频) GraphQL + React Apoll ...
- GraphQL + React Apollo + React Hook 大型项目实战(32 个视频)
GraphQL + React Apollo + React Hook 大型项目实战(32 个视频) GraphQL + React Apollo + React Hook 大型项目实战 #1 介绍「 ...
- 使用graphql和apollo client构建react web应用
graphql是一种用于 API 的查询语言(摘自官网). 我们为什么要用graphql? 相信大家在开发web应用的时候常常会遇到以下这些问题:后端更新了接口却没有通知前端,从而导致各种报错:后端修 ...
- 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 ...
- Android 开发技术周报 Issue#277
新闻 Android 11界面再调整:加入快速截屏.多任务向国产ROM看齐 最新版Android 11推送 谷歌Pixel 5被曝光:支持反向充电 4月Android系统版本分布:8.0 Oreo最主
- Android简单的聊天室开发(client与server沟通)
请尊重他人的劳动成果.转载请注明出处:Android开发之简单的聊天室(client与server进行通信) 1. 预备知识:Tcp/IP协议与Socket TCP/IP 是Transmission ...
- Delphi revelations #1 – kbmMW Smart client on NextGen (Android) – Scope problems
Delphi 启示 #1 – kbmMW Smart client on NextGen (Android) – 作用域问题 以更高级的方式使用kbmMW smart client,在Android设 ...
随机推荐
- Kubernetes --(k8s)yml 文件
认识yml文件 yaml文件语法 大小写敏感 使用缩进表示层级关系 缩进时不允许使用Tab键,只允许使用空格. 缩进的空格数目不重要,只要相同层级的元素左侧对齐即可 # 表示注释,从这个字符一直到行尾 ...
- WinformGDI+入门级实例——扫雷游戏(附源码)
写在前面: 本文将作为一个入门级的.结合源码的文章,旨在为刚刚接触GDI+编程或对相关知识感兴趣的读者做一个入门讲解.游戏尚且未完善,但基本功能都有,完整源码在文章结尾的附件中. 整体思路: 扫雷的游 ...
- ogn1.MethodFailedException:Method "xxx" failed for object xxx
问题描述:初学ssh写了个小项目,访问界面出现以下错误 java. lang. NoSuchllethodError: org. hi bernate. SessionF actory. openSe ...
- 2017-2018 ACM-ICPC, Asia Daejeon Regional Contest PART(10/12)
$$2017-2018\ ACM-ICPC,\ Asia\ Daejeon\ Regional\ Contest$$ \(A.Broadcast\ Stations\) \(B.Connect3\) ...
- Codeforces Round #648 (Div. 2) D. Solve The Maze
这题犯了一个很严重的错误,bfs 应该在入队操作的同时标记访问,而不是每次只标记取出的队首元素. 题目链接:https://codeforces.com/contest/1365/problem/D ...
- 洛谷P3796
题目链接 题意:有n个由小写字母组成的模式串以及一个文本串T.每个模式串可能会在文本串中出现多次.哪些模式串在文本串T中出现的次数最多. 题解:ac自动机模板加强版,开一个数组单独记录各个字符串出现 ...
- 【noi 2.6_2000】&【poj 2127】 最长公共子上升序列 (DP+打印路径)
由于noi OJ上没有Special Judge,所以我是没有在这上面AC的.但是在POJ上A了. 题意如标题. 解法:f[i][j]表示a串前i个和b串前j个且包含b[j]的最长公共上升子序列长度 ...
- Gym 100796K Profact
Alice is bored out of her mind by her math classes. She craves for something much more exciting. Tha ...
- woj1010 alternate sum 数学 woj1011 Finding Teamates 数学
title: woj1010 alternate sum 数学 date: 2020-03-10 categories: acm tags: [acm,woj,数学] 一道数学题.简单. 题意 给一个 ...
- leetcode 12 整数转罗马数字 贪心
额,连着两个贪心? 这是局部最优问题:能用大"罗马数表示"就不会用小的. 先构造出所有基础罗马数,然后从大到小比较 因为比较的只有1000,900,...有限并有些麻烦,构造tab ...