Skip to content

Instantly share code, notes, and snippets.

@Ikhiloya
Created October 28, 2020 07:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ikhiloya/1955a1913b8c28167d548825b1741e0f to your computer and use it in GitHub Desktop.
Save Ikhiloya/1955a1913b8c28167d548825b1741e0f to your computer and use it in GitHub Desktop.
An offline interceptor to cache requests when there is no network connection. It checks if a specific header is present before caching.
open class OfflineCacheInterceptorWithHeader : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
var request = chain.request()
val header = request.headers["Cacheable"]
if (header != null) {
/* check if this request has the [Cacheable] header */
if (header == "true" &&
!PaymentApp.instance!!.isNetworkConnected()
) {
Timber.d("CACHE Header: called.::%s", header)
// prevent caching when network is on. For that we use the "networkInterceptor"
Timber.d("cache interceptor: called.")
val cacheControl = CacheControl.Builder()
.maxStale(7, TimeUnit.DAYS)
.build()
request = request.newBuilder()
.removeHeader(HEADER_PRAGMA)
.removeHeader(HEADER_CACHE_CONTROL)
.cacheControl(cacheControl)
.build()
} else {
Timber.d("cache interceptor: not called.")
}
}
return chain.proceed(request)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment