Thursday, 6 January 2022

OkHttp caching not working when there's internet or not

I'm trying to Make the application uses caching with Okhttp and Retrofit, so the problem that I have now is when I'm using **CacheInterceptor to cache the data** it is getting the data from the internet, and When I'm using **ForceCacheInterceptor to get the data offline** with it, it is not showing any data Whether there is Internet available or not. It is supposed to display Data if there is no Internet, but strange it is not displaying any Data whether there is an Internet or not when used.

So how can I fix this problem, Here's my code


My CacheInterceptor to cache the data

class CacheInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
    val response: Response = chain.proceed(chain.request())
    val cacheControl = CacheControl.Builder()
        .maxAge(10, TimeUnit.DAYS)
        .build()
    return response.newBuilder()
        .header("Cache-Control", cacheControl.toString())
        .build()
   }
}

My ForceCacheInterceptor to get the data offline

class ForceCacheInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
    val builder: Request.Builder = chain.request().newBuilder()
    lateinit var context: Context
    if (!CheckNetwork.isInternetAvailable(context)) {
        builder.cacheControl(CacheControl.FORCE_CACHE);
    }
    return chain.proceed(builder.build());
  }
}

My NetworkLayer, Here I'm using OKhttp and retrofit

private const val BASE_URL = ""
private val moshi: Moshi = Moshi.Builder().addLast(KotlinJsonAdapterFactory()).build()

private fun myHttpClient(): OkHttpClient {
    val builder = OkHttpClient()
        .newBuilder()
        .addNetworkInterceptor(CacheInterceptor()) // only if not enabled from the server
        .addInterceptor(ForceCacheInterceptor())
    return builder.build()
}

private val retrofit: Retrofit = Retrofit.Builder()
    .baseUrl(BASE_URL)
    .client(myHttpClient())
    .addConverterFactory(MoshiConverterFactory.create(moshi))
    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
    .build()

val apiService: APIService by lazy {
    retrofit.create(APIService::class.java)
}

And latest my check network class

object CheckNetwork {
private val TAG = CheckNetwork::class.java.simpleName
fun isInternetAvailable(context: Context): Boolean {
    val info =
        (context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).activeNetworkInfo
    return if (info == null) {
        Log.d(TAG, "no internet connection")
        false
    } else {
        if (info.isConnected) {
            Log.d(TAG, " internet connection available...")
            true
        } else {
            Log.d(TAG, " internet connection")
            true
        }
    }
  }
}


from OkHttp caching not working when there's internet or not

No comments:

Post a Comment