如何使用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设 ...
随机推荐
- login shell 和 non-login shell 的相关问题
问题:通过su命令切换用户并没有进入该用户的shell环境.这是为什么? 要解决这个问题,我们必须清楚用login shell 和non-login shell的区别. login sh ...
- Java 复习整理day08
package com.it.demo02_lambda; //接口, 表示动物. //public abstract class Animal { //报错, Lambda表达式只针对于接口有效 p ...
- CF-1291 D - Irreducible Anagrams
D. Irreducible Anagrams 题意 若两个字符串中每个字符的个数都是一样的,则称他们互为\(anagrams\).现在定义两个字符串s,t是\(reducible~anagram\) ...
- 2019-2020 ACM-ICPC Brazil Subregional Programming Contest (11/13)
\(2019-2020\ ACM-ICPC\ Brazil\ Subregional\ Programming\ Contest\) \(A.Artwork\) 并查集,把检测区域能在一起的检测器放在 ...
- 【poj 2478】Farey Sequence(数论--欧拉函数 找规律求前缀和)
题意:定义 Fn 序列表示一串 <1 的分数,分数为最简分数,且分母 ≤n .问该序列的个数.(2≤N≤10^6) 解法:先暴力找规律(代码见屏蔽处),发现 Fn 序列的个数就是 Φ(1)~Φ( ...
- 正则指引 pdf 高清版
链接:https://pan.baidu.com/s/1Xeuma4toE_L-MxROvTGBxw 提取码:nqyj
- SSM框架整合(Spring + SpringMVC + MyBatis)
搭建环境 使用Spring(业务层)整合其他的框架SpringMVC(表现层)和MyBatis(持久层) Spring框架 创建数据库表 CREATE DATABASE ssm; USE ssm; C ...
- Docker架构分解
Docker总架构分解Docker对使用者来讲是一个C/S模式的架构,而Docker的后端是一个非常松耦合的架构,模块各司其职,并有机组合,支撑Docker的运行. 用户是使用Docker Clien ...
- MySQL 回表查询 & 索引覆盖优化
回表查询 先通过普通索引的值定位聚簇索引值,再通过聚簇索引的值定位行记录数据 建表示例 mysql> create table user( -> id int(10) auto_incre ...
- spring再学习之设计模式
今天我们来聊一聊,spring中常用到的设计模式,在spring中常用的设计模式达到九种. 第一种:简单工厂 三种工厂模式:https://blog.csdn.net/xiaoddt/article/ ...