Created
December 18, 2018 11:09
-
-
Save talenguyen/6cb48654ce4d614f92a41d3fead5e8f1 to your computer and use it in GitHub Desktop.
Make OkHttpClient with cache
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
val cacheSize = (5 * 1024 * 1024).toLong() | |
val cache = Cache(context.cacheDir, cacheSize) | |
// Source https://medium.com/mindorks/caching-with-retrofit-store-responses-offline-71439ed32fda | |
val okHttpClient = OkHttpClient.Builder() | |
// Specify the cache we created earlier. | |
.cache(cache) | |
// Add an Interceptor to the OkHttpClient. | |
.addInterceptor { chain -> | |
// Get the request from the chain. | |
var request = chain.request() | |
/** Leveraging the advantage of using Kotlin, | |
* we initialize the request and change its header depending on whether | |
* the device is connected to Internet or not. | |
*/ | |
request = if (context.isConnected()) | |
/** If there is Internet, get the cache that was stored 5 seconds ago. | |
* If the cache is older than 5 seconds, then discard it, | |
* and indicate an error in fetching the response. | |
* The 'max-age' attribute is responsible for this behavior. | |
*/ | |
request.newBuilder().header("Cache-Control", "public, max-age=" + 5).build() | |
else | |
/** If there is no Internet, get the cache that was stored 7 days ago. | |
* If the cache is older than 7 days, then discard it, | |
* and indicate an error in fetching the response. | |
* The 'max-stale' attribute is responsible for this behavior. | |
* The 'only-if-cached' attribute indicates to not retrieve new data; fetch the cache only instead. | |
*/ | |
request.newBuilder().header( | |
"Cache-Control", | |
"public, only-if-cached, max-stale=" + 60 * 60 * 24 * 7 | |
).build() | |
// End of if-else statement | |
// Add the modified request to the chain. | |
chain.proceed(request) | |
} | |
.addInterceptor(HttpLoggingInterceptor().setLevel(Level.BODY)) | |
.build() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment