I have tried through almost every videos, articles and stackoverflow answer but I am not being able to cache the response in Retrofit.
I have retrofit setup is like this :
private val gson = GsonBuilder()
.setLenient()
.create()!!
private val CACHE_CONTROL = "Cache-Control"
private var cacheSize: Long = 10 * 1024 * 1024 // 10 MB
private var cache = Cache(File(applicationContext.cacheDir, "http-cache"), cacheSize)
private val offlineCacheInterceptor = Interceptor { chain ->
var request = chain.request()
Log.i("datatest", "Internet is availiable : ${isOnline(applicationContext)}")
if (!isOnline(applicationContext)) {
val cacheControl = CacheControl.Builder()
.maxStale(7, TimeUnit.DAYS)
.build()
request = request.newBuilder()
.cacheControl(cacheControl)
.build()
}
chain.proceed(request)
}
private val networkInterceptor = Interceptor { chain ->
val response = chain.proceed(chain.request())
val cacheControl = CacheControl.Builder()
.maxAge(2, TimeUnit.MINUTES)
.build()
response.newBuilder()
.header(CACHE_CONTROL, cacheControl.toString())
.build()
}
private val httpClient = OkHttpClient.Builder()
.addInterceptor(offlineCacheInterceptor)
.addNetworkInterceptor(networkInterceptor)
.cache(cache)
.build()
private val retrofit = Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create(gson))
.client(httpClient)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
But when I try to call the retrofit APIs with my phone in Airplane mode
I get the following error :
Unable to resolve host "my_url": No address associated with hostname
What am I doing wrong in the cache setup?
I think there is a stupid mistake I have done but haven't seen by myself.