Skip to content

Instantly share code, notes, and snippets.

@androidfanatic
Created January 16, 2016 14:01
Show Gist options
  • Save androidfanatic/7d25e699e0149cc320bc to your computer and use it in GitHub Desktop.
Save androidfanatic/7d25e699e0149cc320bc to your computer and use it in GitHub Desktop.
Caching with retrofit 2.0.0
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