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

Learn about previews.

HTTP cache


This page focuses on the HTTP cache. If you want to deduplicate the storage of your objects and/or notify your UI when your data changes, take a look at the normalized cache instead.

note
HTTP caching is only available on the JVM.

Apollo uses OkHttp's cacheUrlOverride to cache GraphQL POST requests when persisted queries and GET requests are not an option.

Setup

Configure your NetworkTransport with your cache-enabled OkHttpClient and cachePostRequests set to true:

Kotlin
1  val apolloClient = ApolloClient.Builder()
2    .networkTransport(
3        HttpNetworkTransport.Builder()
4            // Enable POST caching
5            .httpRequestComposer(DefaultHttpRequestComposer(serverUrl = serverUrl, enablePostCaching = true))
6            .httpEngine(
7                DefaultHttpEngine {
8                  OkHttpClient.Builder()
9                      .cache(directory = File(application.cacheDir, "http_cache"), maxSize = 10_000_000)
10                      .build()
11                }
12            )
13            .build()
14    )
15    .build()

Under the hood, the OkHttp HttpEngine uses "${url}?variablesHash=${variables.sha256()}&operationName=${operation.name()}&operationId=${operation.id()}" as a cacheUrlOverride to cache POST requests.

Usage

OkHttp uses the cache-control header:

Kotlin
1  val successResponse = MockResponse.Builder()
2    .body(FooQuery.successResponse)
3    .addHeader("cache-control", "max-age=100")
4    .build()
5mockServer.enqueue(successResponse)
6
7// first query: goes to the network and caches the response
8val response1 = apolloClient.query(FooQuery()).execute()
9println(response1.isFromHttpCache) // false
10// second query: uses the cached response
11val response2 = apolloClient.query(FooQuery()).execute()
12println(response2.isFromHttpCache) // true

You can use ApolloResponse.isFromHttpCache to determine if a given request comes from the cache:

Kotlin
1  val response = apolloClient.query(FooQuery()).execute()
2assertEquals(false, response.isFromHttpCache)

To disable caching for a particular request, use standard HTTP headers. For example, you can use no-store to disable storing a response:

Kotlin
1  val response1 = apolloClient.query(FooQuery())
2    .addHttpHeader("cache-control", "no-store") // this response is not stored
3    .execute()
4assertEquals(false, response1.isFromHttpCache)
5val response2 = apolloClient.query(FooQuery()) // a new HTTP request is issued.
6    .execute()
7assertEquals(false, response2.isFromHttpCache)
Feedback

Edit on GitHub

Ask Community