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.

ℹ️ The HTTP cache is only available on the JVM.

Setup

To enable HTTP cache support, add the dependency to your project's build.gradle file:

Kotlin
build.gradle[.kts]
1dependencies {
2  implementation("com.apollographql.apollo3:apollo-http-cache:3.8.5")
3}

If you're targeting Android API level < 26, you'll need to enable core library desugaring to support the java.time API:

Kotlin
1android {
2    compileOptions {
3        // Flag to enable support for the new language APIs
4        coreLibraryDesugaringEnabled = true
5    }
6}

Then configure your HTTP cache:

Kotlin
1apolloClient = ApolloClient.Builder()
2    .httpCache(
3      // Use a dedicated directory for the cache
4      directory = File(pathToCacheDirectory),
5      // Configure a max size of 100MB
6      maxSize = 100 * 1024 * 1024
7    )
8    .build()

Usage

The HTTP cache is a least recently used (LRU) cache with a configurable max size.

Once your cache setup is complete, the cache will be used by default by all your queries. By default, queries will try to find a result in the cache first and go the network if it's not there. This is the HttpFetchPolicy.CacheFirst. You can customize that behaviour with httpFetchPolicy(HttpFetchPolicy):

Kotlin
1val response = apolloClient.query(query)
2                 // Don't use the cache
3                 .httpFetchPolicy(HttpFetchPolicy.NetworkOnly)
4
5                 // Or only use the cache
6                 .httpFetchPolicy(HttpFetchPolicy.CacheOnly)
7
8                 // Finally, execute your query
9                 .execute()

If the query is present in cache, it will be used to return response.data. If not, a HttpCacheMissException will be thrown.

You can also set an expiration time either globally or for specific queries. The entries will automatically be removed from the cache after the expiration time:

Kotlin
1// Globally
2apolloClient = ApolloClient.Builder()
3    .httpCache(/*...*/)
4    // Expire after 1 hour
5    .httpExpireTimeout(60 * 60 * 1000)
6    .build()
7
8// On a specific query
9val response = apolloClient.query(query)
10    // Expire after 1 hour
11    .httpExpireTimeout(60 * 60 * 1000)
12    .execute()

If a specific query must not be cached, you can use httpDoNotStore():

Kotlin
1val response = apolloClient.query(query)
2    // Don't cache this query
3    .httpDoNotStore(httpDoNotStore = true)
4    .execute()

Clearing the cache

Call apolloClient.httpCache.clearAll() to clear the cache of all entries.

Edit on GitHub

Forums