HTTP cache
Apollo Android provides two different kinds of caches: an HTTP cache and a normalized cache. The HTTP cache is easier to set up but also has more limitations. 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.
HTTP cache
To enable HTTP cache support, add the dependency to your project's `build.gradle file. The latest version is
1dependencies {
2 implementation("com.apollographql.apollo:apollo-http-cache:x.y.z")
3}
Raw HTTP response cache
1// Directory where cached responses will be stored
2val file = File(cacheDir, "apolloCache")
3
4// Size in bytes of the cache
5val size: Long = 1024 * 1024
6
7// Create the http response cache store
8val cacheStore = DiskLruHttpCacheStore(file, size)
9
10// Build the ApolloClient
11val apolloClient = ApolloClient.builder()
12 .serverUrl("/")
13 .httpCache(ApolloHttpCache(cacheStore))
14 .okHttpClient(okHttpClient)
15 .build()
16
17// Control the cache policy
18val query = FeedQuery(limit = 10, type = FeedType.HOT)
19val dataResponse = apolloClient.query(query)
20 .httpCachePolicy(HttpCachePolicy.CACHE_FIRST)
21 .toDeferred()
22 .await()
1//Directory where cached responses will be stored
2File file = new File(cacheDir, "apolloCache");
3
4//Size in bytes of the cache
5long size = 1024*1024;
6
7//Create the http response cache store
8DiskLruHttpCacheStore cacheStore = new DiskLruHttpCacheStore(file, size);
9
10//Build the ApolloClient
11ApolloClient apolloClient = ApolloClient.builder()
12 .serverUrl("/")
13 .httpCache(new ApolloHttpCache(cacheStore))
14 .okHttpClient(okHttpClient)
15 .build();
16
17apolloClient
18 .query(
19 FeedQuery.builder()
20 .limit(10)
21 .type(FeedType.HOT)
22 .build()
23 )
24 .httpCachePolicy(HttpCachePolicy.CACHE_FIRST)
25 .enqueue(new ApolloCall.Callback<FeedQuery.Data>() {
26 @Override public void onResponse(@NotNull Response<FeedQuery.Data> dataResponse) {
27 ...
28 }
29
30 @Override public void onFailure(@NotNull Throwable t) {
31 ...
32 }
33 });
IMPORTANT: Caching is provided only for query
operations. It isn't available for mutation
operations.
There are four available cache policies HttpCachePolicy
:
NETWORK_ONLY
- Fetch a response from the network only, ignoring any cached responses. This is the default.CACHE_ONLY
- Fetch a response from the cache only, ignoring the network. If the cached response doesn't exist or is expired, then return an error.CACHE_FIRST
- Fetch a response from the cache first. If the response doesn't exist or is expired, then fetch a response from the network.NETWORK_FIRST
- Fetch a response from the network first. If the network fails and the cached response isn't expired, then return cached data instead.
For CACHE_ONLY
, CACHE_FIRST
and NETWORK_FIRST
policies you can define the timeout after what cached response is treated as expired
and will be evicted from the http cache, expireAfter(expireTimeout, timeUnit)
.`