Last active
October 28, 2020 07:13
-
-
Save Ikhiloya/18756d2da36c1181f868c4308310c032 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 annotation is present before caching.
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
open class OfflineCacheInterceptor : Interceptor { | |
override fun intercept(chain: Interceptor.Chain): Response { | |
var request = chain.request() | |
val invocation: Invocation? = request.tag(Invocation::class.java) | |
if (invocation != null) { | |
val annotation: Cacheable? = | |
invocation.method().getAnnotation(Cacheable::class.java) | |
/* check if this request has the [Cacheable] annotation */ | |
if (annotation != null && | |
annotation.annotationClass.simpleName.equals("Cacheable") && | |
!PaymentApp.instance!!.isNetworkConnected() | |
) { | |
Timber.d("CACHE ANNOTATION: called.::%s", annotation.annotationClass.simpleName) | |
// 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