Retrofit 2 - how to set dynamic cache time to different endpoint

Viewed 1056

I need to set different cache time to different endpoints, what are the best practices for that?

This is my Retrofit interface:

public interface ServerApi {

@GET("a1")// need to get 10 mintuns cache time
Observable<A1> getA1();

@GET("a2")// need to get 20 mintuns cache time
Observable<A2> getA2();

@GET("a3")// need to get 30 mintuns cache time
Observable<A3> getA3();

This is my network class:

public class Network {
Network() {
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .addNetworkInterceptor(logging)
            .build();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BuildConfig.BASE_URL)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient)
            .build();

    retrofit.create(ServerApi.class);
}}
1 Answers

If your server provides correct cache-control headers. OkHttp will handle the caching for you.

Init cache for your Retrofit client

int cacheSize = 10 * 1024 * 1024;
Cache cache = new Cache(app.getCacheDir(), cacheSize);

Build OkHttp client, provide cache

OkHttpClient client = new OkHttpClient.Builder()
            // Add cache
            .cache(cache)
            .build();

Build Retrofit

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(RxJavaCallAdapterFactory
                    .createWithScheduler(Schedulers.newThread()))
            // Add OkHttp client
            .client(client)
            .build();

If for some reason your server does not provide cache-headers. You can always hardcode request interceptors and add cache-headers on the client side.

You could probably use some combination of these:

Cache-Control: max-age=<seconds>
Cache-Control: max-stale[=<seconds>]

But if you decide to do that, ask a simple question. What if I decide to change expiry times? You'd probably end up writing some unnecessary code or ship a new APK version. Not cool.

Good luck.

Related