监控网络状态以减少延迟
网络监控API目前正处于Apollo Kotlin中的
Android和Apple的目标提供API来监控你的设备网络状态。
- ConnectivityManager在Android目标中使用。
- NWPathMonitor在Apple目标中使用。
您可以配置您的ApolloClient,通过使用NetworkMonitor
API来改进请求的延迟:
// androidMainval networkMonitor = NetworkMonitor(context)// appleMainval networkMonitor = NetworkMonitor()// commonMainval apolloClient = ApolloClient.Builder().serverUrl("https://example.com/graphql").retryOnErrorInterceptor(RetryOnErrorInterceptor(networkMonitor)).build()
failFastIfOffline
当配置了NetworkMonitor
后,您可以使用failFastIfOffline
来避免设备离线时尝试发送请求:
// Opt-in `failFastIfOffline` on all queriesval apolloClient = ApolloClient.Builder().serverUrl("https://example.com/graphql").failFastIfOffline(true).build()val response = apolloClient.query(myQuery).execute()println(response.exception?.message)// "The device is offline"// Opt-out `failFastIfOffline` on a single queryval response = apolloClient.query(myQuery).failFastIfOffline(false).execute()
retryOnError
当配置了NetworkMonitor
后,retryOnError
会使用NetworkMonitor.waitForNetwork()
而不是默认的指数退避算法,以便在连接恢复后更快地重新连接。
自定义重试算法
您可以通过定义自己的拦截器进一步自定义重试算法
val apolloClient = ApolloClient.Builder().retryOnErrorInterceptor(MyRetryOnErrorInterceptor()).build()class MyRetryOnErrorInterceptor : ApolloInterceptor {object RetryException : Exception()override fun <D : Operation.Data> intercept(request: ApolloRequest<D>, chain: ApolloInterceptorChain): Flow<ApolloResponse<D>> {var attempt = 0return chain.proceed(request).onEach {if (request.retryOnError == true && it.exception != null && it.exception is ApolloNetworkException) {throw RetryException} else {attempt = 0}}.retryWhen { cause, _ ->if (cause is RetryException) {attempt++delay(2.0.pow(attempt).seconds)true} else {// Not a RetryException, probably a programming error, pass it throughfalse}}}}