如何使用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. Spring Cloud与Docker——微服务架构概述

    Spring Cloud与Docker--微服务架构概述 单体应用架构概述 微服务概述 微服务的特性 微服务架构的优点 微服务面临的挑战 微服务的设计原则 单体应用架构概述 传统的服务发布都是采用单体 ...

  2. hbase 集群(完全分布式)方式安装

    一,环境 1,  主节点一台: ubuntu desktop 16.04 zhoujun      172.16.12.1 从节点(slave)两台:ubuntu server 16.04 hadoo ...

  3. pandas中的遍历方式速度对比

    对一个20667行的xlsx文件进行遍历测试 import pandas as pd # 定义一个计算执行时间的函数作装饰器,传入参数为装饰的函数或方法 def print_execute_time( ...

  4. Flink-v1.12官方网站翻译-P028-Custom Serialization for Managed State

    管理状态的自定义序列化 本页面的目标是为需要使用自定义状态序列化的用户提供指导,涵盖了如何提供自定义状态序列化器,以及实现允许状态模式演化的序列化器的指南和最佳实践. 如果你只是简单地使用Flink自 ...

  5. PTA甲级—链表

    1032 Sharing (25分) 回顾了下链表的基本使用,这题就是判断两个链表是否有交叉点. 我最开始的做法就是用cnt[]记录每个节点的入度,发现入度为2的节点即为答案.后来发现这里忽略了两个链 ...

  6. Codeforces Round #660 (Div. 2) A. Captain Flint and Crew Recruitment、Captain Flint and a Long Voyage

    题目链接:Captain Flint and Crew Recruitment 题意: t组输入,每一组输入一个n.这里我们说一下题目定义的近似质数概念: "如果可以将正整数x表示为p⋅q, ...

  7. poj2926Requirements (曼哈顿距离)

    Description An undergraduate student, realizing that he needs to do research to improve his chances ...

  8. Educational Codeforces Round 94 (Rated for Div. 2) D. Zigzags (枚举,前缀和)

    题意:有一长度为\(n(4\le n\le 3000)\)的数组,选择四个位置\((i,j,k,l)\ (1\le i<j<k\le n)\),使得\(a_i=a_k\)并且\(a_j=a ...

  9. Codeforces Round #681 (Div. 2, based on VK Cup 2019-2020 - Final) B. Saving the City (贪心,模拟)

    题意:给你一个\(01\)串,需要将所有的\(1\)给炸掉,每次炸都可以将一整个\(1\)的联通块炸掉,每炸一次消耗\(a\),可以将\(0\)转化为\(1\),消耗\(b\),问将所有\(1\)都炸 ...

  10. POJ2785 4 Values whose Sum is 0 (二分)

    题意:给你四组长度为\(n\)序列,从每个序列中选一个数出来,使得四个数字之和等于\(0\),问由多少种组成情况(仅于元素的所在位置有关). 题解:\(n\)最大可以取4000,直接暴力肯定是不行的, ...