You are viewing documentation for a preview version of this software.

Learn about previews.

Monitor the network state to reduce latency


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    .retryOnErrorInterceptor(RetryOnErrorInterceptor(networkMonitor))
5    .failFastIfOffline(true)
6    .build()
7
8val response = apolloClient.query(myQuery).execute()
9println(response.exception?.message)
10// "The device is offline"
11
12// Opt-out `failFastIfOffline` on a single query
13val 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

To customize the retry algorithm, use a RetryStrategy. The following example shows a RetryStrategy that uses exponential backoff and gives up after four tries:

Kotlin
1val apolloClient = ApolloClient.Builder()
2    .retryOnErrorInterceptor(RetryOnErrorInterceptor(networkMonitor) { state, request, response,  ->
3      val exception = response.exception
4      if (exception == null) {
5        return@RetryOnErrorInterceptor false
6      }
7
8      delay(2.0.pow(state.attempt).seconds)
9      state.attempt++
10      return@RetryOnErrorInterceptor state.attempt < 4
11    })
12    .build()
Feedback

Edit on GitHub

Ask Community