Join us from October 8-10 in New York City to learn the latest tips, trends, and news about GraphQL Federation and API platform engineering.Join us for GraphQL Summit 2024 in NYC
Docs
Start for Free
You're viewing documentation for an upcoming version of this software. Switch to the latest stable version.

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:

You can configure your ApolloClient to use these APIs to improve latency of your requests using the NetworkMonitor API:

// androidMain
val networkMonitor = NetworkMonitor(context)
// appleMain
val networkMonitor = NetworkMonitor()
// commonMain
val apolloClient = ApolloClient.Builder()
.serverUrl("https://example.com/graphql")
.retryOnErrorInterceptor(RetryOnErrorInterceptor(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 queries
val 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 query
val 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 own interceptor:

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 mechanism
val 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 here
true
} else {
// Programming error, re-throw it
false
}
}
}
}
Previous
Uploading files
Next
Handling nullability
Rate articleRateEdit on GitHubEditForumsDiscord

© 2024 Apollo Graph Inc., d/b/a Apollo GraphQL.

Privacy Policy

Company