Last active
February 4, 2018 17:36
-
-
Save mohsenoid/ec00ab55b26c8d153fdcb8de5765f075 to your computer and use it in GitHub Desktop.
Sample ClientModule HttpCacheInterceptors https://hackernoon.com/yet-another-mvp-article-part-3-calling-apis-using-retrofit-23757f4eee05
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
@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