Giter Site home page Giter Site logo

cachingwithretrofit's Introduction

CachingWithRetrofit

Simple way to cache your request with help of retrofit http (Store data offline )

For more detail (max-age, max-stale and only-if-cached):

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control

alt text

alt text

Download APK :

https://github.com/datanapps/CachingWithRetrofit/blob/master/screens/app-debug.apk

Interceptor

The idea of interceptor is that it should serve as the gateway for all the API requests your application fires. So that there is single point of change for requirements that span across all the calls.

Retrofit Network Client (add interceptor):

if your app has a limit (1-8) on the number of requests you can make :

public class NetworkClient {


private static final String BASE_URL = "https://reqres.in";

private static final int TIMEOUT = 10;
private static final long cacheSize = 5 * 1024 *1024 ; // 5 x 1024 x 1024

public static Retrofit retrofit;
public static Retrofit getRetrofitClient(final Context context) {
    if (retrofit == null) {
        Cache myCache = new Cache(context.getCacheDir(), cacheSize);
        OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
        okHttpClientBuilder.connectTimeout(TIMEOUT, TimeUnit.SECONDS);
        okHttpClientBuilder.cache(myCache);
        okHttpClientBuilder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();

                if (Utils.isNetworkConnected(context)) {
                    request.newBuilder().header("Cache-Control", "public, max-age=" + 5).build();
                } else {
                    request.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + 60 * 60 * 24 * 7).build();
                }


                return chain.proceed(request);
            }
        });

        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClientBuilder.build())
                .build();
    }
    return retrofit;
}

 }

Retrofit Network Client :

if you want to work for more then 10 api then you can use intercepter and network interceptor:
 package datanapps.caching.retrofit.network;

import java.io.File;
import java.io.IOException;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import datanapps.caching.retrofit.BuildConfig;
import datanapps.caching.retrofit.CachingWithRetrofitApp;
import datanapps.caching.retrofit.utils.Utils;
import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitClient {


private static final String BASE_URL = "https://reqres.in";

private static final int TIMEOUT = 10;

/**
 * The overridden cache duration to keep data from GET requests.
 * Currently set to 10 minutes
 */
private static final int CACHE_DURATION_MIN = 10;

/**
 * The overridden cache duration to keep data from GET requests.
 * Currently set to 10 minutes
 */
private static final long CACHE_DURATION_SEC = 600;

/**
 * The overridden stale duration in seconds.
 * Currently set to 7 days
 */
private static final int STALE_DURATION_DAYS = 7;

/**
 * Max size of OkHTTP cache -- currently 50 MB
 */
private static final int HTTP_CACHE_MAX_SIZE = 50 * 1024 * 1024;

/**
 * The directory name to place cache files from OkHttp. This directory will be placed in the
 * app's internal cache directory (or external if this is a debug build)
 */
private static final String HTTP_CACHE_DIR = "ccachingwithretrofit_cache";



public static Retrofit retrofit;


public static Retrofit getRetrofitClient() {
    if (retrofit == null) {
        Cache myCache = getHttpCache();
        OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
        okHttpClientBuilder.connectTimeout(TIMEOUT, TimeUnit.SECONDS);
        okHttpClientBuilder.cache(myCache);
        okHttpClientBuilder.addInterceptor(rewriteRequestInterceptor);
        okHttpClientBuilder.addNetworkInterceptor(REWRITE_RESPONSE_CACHE_CONTROL_INTERCEPTOR);

        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClientBuilder.build())
                .build();
    }
    return retrofit;
}

private static Cache getHttpCache() {
    final File cacheDir;
    if (BuildConfig.DEBUG) {
        cacheDir = new File(CachingWithRetrofitApp.getAppContext().getExternalCacheDir(), HTTP_CACHE_DIR);
    } else {
        cacheDir = new File(CachingWithRetrofitApp.getAppContext().getCacheDir(), HTTP_CACHE_DIR);
    }
    return new Cache(cacheDir, HTTP_CACHE_MAX_SIZE);
}

private static final Interceptor rewriteRequestInterceptor = new Interceptor() {
    @Override
    public Response intercept(final Chain chain) throws IOException {
        Request request = chain.request();

        if (request.cacheControl().noCache()) {
            return chain.proceed(request);
        }

        if (Utils.isNetworkConnected(CachingWithRetrofitApp.getAppContext())) {
            // the data can be reused for CACHE_DURATION_MIN
            request = request.newBuilder()
                    .cacheControl(new CacheControl.Builder().maxStale(CACHE_DURATION_MIN, TimeUnit.MINUTES).build())
                    .build();
        }
        else {
            // for offline
            request = request.newBuilder()
                    .cacheControl(new CacheControl.Builder().onlyIfCached()
                            .maxStale(STALE_DURATION_DAYS,
                                    TimeUnit.DAYS)
                            .build())
                    .build();
        }

        return chain.proceed(request);
    }
};



// this for only response interceptor is invoked for online responses
private static final Interceptor REWRITE_RESPONSE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Response originalResponse = chain.proceed(chain.request());
        int maxAge = originalResponse.cacheControl().maxAgeSeconds();
        if (maxAge <= 0) {
            return originalResponse.newBuilder()
                    .removeHeader("Pragma")
                    .removeHeader("Expires")
                    .removeHeader("Cache-Control")
                    .header("Cache-Control", String.format(Locale.ENGLISH, "max-age=%d, only-if-cached, max-stale=%d", CACHE_DURATION_SEC, 0))
                    .build();
        } else {
            return originalResponse;
        }
    }
};

}

See

License

Copyright [2021] [datanapps]

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0

cachingwithretrofit's People

Contributors

datanapps avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.