Retrofit Offline Caching or Response Caching in Android

Hello friends,

Today I am posting about the caching in Retrofit, a network library in Android.

As we know caching is controlled by the Http Headers which are sent by the server in response.
Here we a use a powerful feature of Retrofit library of Intercepting the Request or Reponses.Interceptors are used to intercept and modify the request and responses.

We can use the caching in two ways -

1. There are some cases when identical request is made within a small period of time such as within 60 seconds, in such cases we can use cache to fetch the same response of the request that was fetched last time instead of makig a new API request.

2.Also we can use the response that was last fetched so that we can show the same response when the device is offline.

First create "ResponseCachingInterceptor" class that implements the Interceptor interface from okhttp class as below.
This is basically used for caching the network response for a minute.

    private static class ResponseCachingInterceptor implements Interceptor {

        @Override
            public Response intercept(Chain chain) throws IOException {
            Response response = chain.proceed(chain.request());
            return response.newBuilder()
                    .removeHeader("Pragma")
                    .removeHeader("Access-Control-Allow-Origin")
                    .removeHeader("Vary")
                    .removeHeader("Cache-Control")
                    .header("Cache-Control", "public, max-age=60")
                    .build();
        }
    }

Here we overiding the intercept method.
The "chain.proceed" returns the reponse of the Api request and then we modify its headers to implement caching.
First we remove some headers such as "Pragma","Cache-Control" and others to remove misconfiguration in these headers.
And then we add the "Cache-Control" header that is responsible for the caching.Here we use "max-age=60" to set the time-frame of 60 seconds.

Now we will create the "OfflineResponseCacheInterceptor" for offline cache handling as below-

          private static class OfflineResponseCacheInterceptor implements Interceptor {
           @Override            
           public okhttp3.Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                NetworkInfo networkInfo =((ConnectivityManager) 
                (context.getSystemService(Context.CONNECTIVITY_SERVICE))).getActiveNetworkInfo();
                if (networkInfo==null) {
                    request = request.newBuilder()
                            .removeHeader("Pragma")
                            .removeHeader("Access-Control-Allow-Origin")
                            .removeHeader("Vary")
                            .removeHeader("Cache-Control")
                            .header("Cache-Control",
                                    "public, only-if-cached, max-stale= 60")
                            .build();
                }
                return chain.proceed(request);
            }
        }

Here again we remove some header and the override the "Cache-Control" header as 
"public, only-if-cached, max-stale=60"
Here max-stale=60 denotes the expiration of cached response.After that time it will return with status code = 504 if network is not available otherwise it will revalidate the response from the server.


Now you can apply these interceptors to the okhttpclient as given below-

OkHttpClient okHttpClient = new OkHttpClient.Builder()
        //Enable Response Caching
        .addNetworkInterceptor(new ResponseCachingInterceptor())
        //Enable Offline Response Caching
        .addInterceptor(new OfflineResponseCacheInterceptor())
        .cache(cache)
        .build();

And that's all we need to implement caching in Retrofit.
The above approach to caching is what Retrofit uses and it works pretty well if the right headers are sent.You just have to define the cache location and headers, everything is pretty much handled by the library.
   

15 comments:

  1. This is one freaking good article. The way you've written. The amount of information and how good information you've given is just incredible. flutter app development company

    ReplyDelete
  2. Thanks For Sharing this Valuable Information from Smiligence

    ReplyDelete
  3. Náhradné diely pre mobilné telefóny Apple, Samsung, Huawei. ochranne sklo

    ReplyDelete
  4. Thanks For Sharing This Valuable Information From Managed Services

    ReplyDelete
  5. Thanks for sharing this nice information blogs. We are a flutter app development company in the USA.

    ReplyDelete
  6. Took me time to read all the comments, but I really enjoyed the article. It proved to be Very helpful to me and I am sure to all the commenters here! It’s always nice when you can not only be informed, but also entertained! Child names

    ReplyDelete
  7. Thanks for sharing this nice information blogs. We are a flutter app development company in the USA.

    ReplyDelete
  8. Nice and Informative post also like to read my post Colour Prediction App

    ReplyDelete
  9. This article offers a great explanation of how to implement caching in Retrofit for both online and offline scenarios. The step-by-step guide on using interceptors and managing cache headers is really helpful for improving app performance and handling network requests efficiently. A must-read for Android developers working with Retrofit.

    Visit now - App Development Sydney

    ReplyDelete
  10. Nursing professionals in Saudi Arabia can expect attractive salaries that align with the region's demand for skilled healthcare workers. Entry-level positions typically offer compensation ranging from SAR 4,000 to SAR 6,000 per month, while more experienced nurses can earn between SAR 7,000 and SAR 12,000, depending on their specialization and experience. This competitive salary is further enhanced by benefits such as free accommodation, transportation allowances, and comprehensive health coverage. One of the most appealing aspects is the tax-free status of this income, significantly boosting take-home pay. Additionally, Saudi Arabia provides numerous opportunities for career advancement, making it an appealing destination for international nurses.
    https://www.dynamichealthstaff.com/nurse-salary-in-saudi-arabia

    ReplyDelete

Flutter : Using Form and Text Fields

Flutter is a popular cross-platform mobile development framework that allows developers to build native apps for both Android and iOS using ...