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:

Kotlin
1// androidMain
2val networkMonitor = NetworkMonitor(context)
3
4// appleMain
5val networkMonitor = NetworkMonitor()
6
7// commonMain
8val apolloClient = ApolloClient.Builder()
9    .serverUrl("https://example.com/graphql")
10    .retryOnErrorInterceptor(RetryOnErrorInterceptor(networkMonitor))
11    .build()
12
13// once you're done with your `ApolloClient`
14networkMonitor.close()

failFastIfOffline

When a NetworkMonitor is configured, you can use failFastIfOffline to avoid trying out request if the device is offline:

Kotlin
1// Opt-in `failFastIfOffline` on all queries
2val apolloClient = ApolloClient.Builder()
3    .serverUrl("https://example.com/graphql")
4    .failFastIfOffline(true)
5    .build()
6
7val response = apolloClient.query(myQuery).execute()
8println(response.exception?.message)
9// "The device is offline"
10
11// Opt-out `failFastIfOffline` on a single query
12val 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 your own interceptor:

Kotlin
1val apolloClient = ApolloClient.Builder()
2    .retryOnErrorInterceptor(MyRetryOnErrorInterceptor())
3    .build()
4
5class MyRetryOnErrorInterceptor : ApolloInterceptor {
6  object RetryException : Exception()
7
8  override fun <D : Operation.Data> intercept(request: ApolloRequest<D>, chain: ApolloInterceptorChain): Flow<ApolloResponse<D>> {
9    var attempt = 0
10    return chain.proceed(request).onEach {
11      if (request.retryOnError == true && it.exception != null && it.exception is ApolloNetworkException) {
12        throw RetryException
13      } else {
14        attempt = 0
15      }
16    }.retryWhen { cause, _ ->
17      if (cause is RetryException) {
18        attempt++
19        delay(2.0.pow(attempt).seconds)
20        true
21      } else {
22        // Not a RetryException, probably a programming error, pass it through
23        false
24      }
25    }
26  }
27}
Feedback

Edit on GitHub

Forums