Monitor the network state to reduce latency
Network Monitor APIs are currently experimental in Apollo Kotlin. If you have feedback on them, please let us know via GitHub issues or in the Kotlin Slack community.
Android and Apple targets provide APIs to monitor the network state of your device:
- ConnectivityManager on Android targets.
- NWPathMonitor on Apple targets.
You can configure your ApolloClient to use these APIs to improve latency of your requests using the NetworkMonitor
API:
// androidMainval networkMonitor = NetworkMonitor(context)// appleMainval networkMonitor = NetworkMonitor()// commonMainval apolloClient = ApolloClient.Builder().serverUrl("https://example.com/graphql").networkMonitor(networkMonitor).build()
failFastIfOffline
When a NetworkMonitor
is configured, you can use failFastIfOffline
to avoid trying out request if the device is offline:
// 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
When a NetworkMonitor
is configured, retryOnError
uses NetworkMonitor.waitForNetwork()
instead of the default exponential backoff algorithm in order to reconnect faster when connectivity is back.
Customizing the retry algorithm
You can customize the retry algorithm further by defining you won interceptor. Make sure to:
- add your interceptor last, so that it wraps the network call and doesn't get cache misses or any other errors that may be emitted by upstream interceptors.
- call
retryOnError(false)
when forwarding the request downstream so that the retry is not made twice.
internal class MyRetryInterceptor(private val networkMonitor: NetworkMonitor?): ApolloInterceptor {override fun <D : Operation.Data> intercept(request: ApolloRequest<D>, chain: ApolloInterceptorChain): Flow<ApolloResponse<D>> {// Disable Apollo's built-in retry mechanismval newRequest = request.newBuilder().retryOnError(false).build()return chain.proceed(newRequest).onEach {if (it.exception != null && it.exception.shouldRetry()) {throw RetryException}}.retryWhen { cause, _->if (cause is RetryException) {// Add your logic heretrue} else {// Programming error, re-throw itfalse}}}}