Skip to content

Instantly share code, notes, and snippets.

@mohsenoid
Last active February 4, 2018 17:36
Show Gist options
  • Save mohsenoid/ec00ab55b26c8d153fdcb8de5765f075 to your computer and use it in GitHub Desktop.
Save mohsenoid/ec00ab55b26c8d153fdcb8de5765f075 to your computer and use it in GitHub Desktop.
@Provides
@Singleton
public Cache provideCache(@Named("cacheDir") File cacheDir, @Named("cacheSize") long cacheSize) {
Cache cache = null;
try {
cache = new Cache(new File(cacheDir.getPath(), HTTP_CACHE_PATH), cacheSize);
} catch (Exception e) {
e.printStackTrace();
}
return cache;
}
@Singleton
@Provides
@Named("cacheInterceptor")
public Interceptor provideCacheInterceptor(@Named("cacheMaxAge") int maxAgeMin) {
return chain -> {
Response response = chain.proceed(chain.request());
CacheControl cacheControl = new CacheControl.Builder()
.maxAge(maxAgeMin, TimeUnit.MINUTES)
.build();
return response.newBuilder()
.header(CACHE_CONTROL, cacheControl.toString())
.build();
};
}
@Singleton
@Provides
@Named("offlineInterceptor")
public Interceptor provideOfflineCacheInterceptor(StateManager stateManager, @Named("cacheMaxStale") int maxStaleDay) {
return chain -> {
Request request = chain.request();
if (!stateManager.isConnect()) {
CacheControl cacheControl = new CacheControl.Builder()
.maxStale(maxStaleDay, TimeUnit.DAYS)
.build();
request = request.newBuilder()
.cacheControl(cacheControl)
.build();
}
return chain.proceed(request);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment