Created
January 16, 2016 14:01
-
-
Save androidfanatic/7d25e699e0149cc320bc to your computer and use it in GitHub Desktop.
Caching with retrofit 2.0.0
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private OkHttpClient getCacheClient(final Context context) { | |
Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() { | |
@Override public okhttp3.Response intercept(Chain chain) throws IOException { | |
okhttp3.Response originalResponse = chain.proceed(chain.request()); | |
if (isNetworkAvailable(MainApp.getContext())) { | |
// Internet available; read from cache for 1 day | |
// Why? Reduce server load, better UX | |
int maxAge = 60 * 60 * 24; | |
return originalResponse.newBuilder() | |
.header("Cache-Control", "public, max-age=" + maxAge) | |
.build(); | |
} else { | |
// No internet; tolerate cached data for 1 week | |
int maxStale = 60 * 60 * 24 * 7; | |
return originalResponse.newBuilder() | |
.header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale) | |
.build(); | |
} | |
} | |
}; | |
File httpCacheDirectory = new File(context.getCacheDir(), "cachedir"); | |
int size = 5 * 1024 * 1024; | |
Cache cache = new Cache(httpCacheDirectory, size); | |
return new OkHttpClient.Builder() | |
.addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR) | |
.cache(cache) | |
.build(); | |
} | |
// Usage: | |
MovieApi movieApi = new Retrofit.Builder() | |
.baseUrl(MovieApi.URL) | |
.client(getCacheClient(MainApp.getContext())) // set cache client | |
.addConverterFactory(GsonConverterFactory.create() | |
.build() | |
.create(MovieApi.class); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment