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.
Setup
To enable HTTP cache support, add the dependency to your project's build.gradle file:
1dependencies { 2 implementation("com.apollographql.apollo:apollo-http-cache:4.3.3") 3}If you're targeting Android API level < 26, you'll need to enable core library desugaring to support the java.time API:
1android { 2 compileOptions { 3 // Flag to enable support for the new language APIs 4 coreLibraryDesugaringEnabled = true 5 } 6}Then configure your HTTP cache:
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 policy. You can customize that behaviour with httpFetchPolicy(HttpFetchPolicy):
1val response = apolloClient.query(query) 2 // Try the cache first - if it's a miss, try the network 3 .httpFetchPolicy(HttpFetchPolicy.CacheFirst) 4 5 // Only use the cache 6 .httpFetchPolicy(HttpFetchPolicy.CacheOnly) 7 8 // Try the network first - if there's an error, try the cache 9 .httpFetchPolicy(HttpFetchPolicy.NetworkFirst) 10 11 // Don't use the cache 12 .httpFetchPolicy(HttpFetchPolicy.NetworkOnly) 13 14 // Finally, execute your query 15 .execute()Note: mutations and subscriptions don't go through the cache.
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:
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():
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.