I want to cache 200 requests and retrive data from cache when don’t have internet/meet some api errors, but cannot get any data from cache:

My network interceptor

override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val originalResponse = chain.proceed(request)

// Only cache responses with status code 200
if (originalResponse.code == 200) {
    val cacheResponse =  originalResponse.newBuilder()
        .header(
            name = HeadersFields.CACHE_CONTROL,
            value = HeadersFields.getPublicMaxAgeHeader(cacheTimeInSecond = 3600
            )
        )
        .removeHeader(name = HeadersFields.PRAGMA)
        .build()
    return cacheResponse
}

return originalResponse
}

App interceptor

override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()

val cacheRequest =
    request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).removeHeader(name = HeadersFields.PRAGMA).build()

return try {
    chain.proceed(request)
} catch (e: Exception) {
    when (e) {
        is ServerError, is SocketTimeoutException, is TimeoutException, is ConnectException -> {
            chain.proceed(cacheRequest)
        }
        else -> chain.proceed(request)
    }
}
}

I inject okhttp client instance to both interceptors in order to monitor cache and I see records (that increase after next requests)
enter image description here

But I got

(httpStatusCode=504, httpMessage=Unsatisfiable Request (only-if-cached), responseBody=)
Blockquote

My client ( Ive got only one OkHttpClient that inject everywhere). I set up maxRequestsPerHost to 1 to avoid race condition, but it doesn’t help :/

private const val CONNECT_TIMEOUT_SEC = 60L
private const val CACHE_MAX_SIZE = 50L * 1024L * 1024L

    fun getOkHttpClient(context: Context): OkHttpClient {
        val appCache = Cache(directory = context.cacheDir, maxSize = CACHE_MAX_SIZE)
        val client = OkHttpClient.Builder().apply {
            cache(appCache)
            connectTimeout(timeout = CONNECT_TIMEOUT_SEC, unit = TimeUnit.SECONDS)
        }.build()
        client.dispatcher.maxRequestsPerHost = 1
        return client
    }