Skip to content

Instantly share code, notes, and snippets.

@bapspatil
Last active January 4, 2021 19:39
Show Gist options
  • Save bapspatil/1111ee6e6bccfed3f91efb290f85e828 to your computer and use it in GitHub Desktop.
Save bapspatil/1111ee6e6bccfed3f91efb290f85e828 to your computer and use it in GitHub Desktop.
OkHttpClient (SHORT) for caching
val okHttpClient = OkHttpClient.Builder()
// Specify the cache we created earlier.
.cache(myCache)
// 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 (hasNetwork(context)!!)
/*
* 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)
}
.build()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment