Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if OkHttp response comes from cache (with Retrofit)

Is there a way to detect if a Retrofit response comes from the configured OkHttp cache or is a live response?

Client definition:

Cache cache = new Cache(getCacheDirectory(context), 1024 * 1024 * 10);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .cache(cache)
            .build();

Api definition:

@GET("/object")
Observable<Result<SomeObject>> getSomeObject();

Example call:

RetroApi retroApi = new Retrofit.Builder()
            .client(okHttpClient)
            .baseUrl(baseUrl)
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(RetroApi.class);

result = retroApi.getSomeObject().subscribe((Result<SomeObject> someObjectResult) -> {
     isFromCache(someObjectResult); // ???
});
like image 418
whlk Avatar asked Jan 18 '17 19:01

whlk


People also ask

Does retrofit use OkHttp?

In contrast, Retrofit is a high-level REST abstraction build on top of OkHttp. Retrofit is strongly coupled with OkHttp and makes intensive use of it.

What is OkHttp cache?

OkHttp is an efficient HTTP & HTTP/2 client for Android and Java applications. It comes with advanced features, such as connection pooling (if HTTP/2 isn't available), transparent GZIP compression, and response caching, to avoid the network completely for repeated requests.

Can I delete OkHttp cache?

You can use the clear cache method to clear the picasso cache.


1 Answers

Any time you have an okhttp3.Response (retrofit2.Response.raw()), you can check if the response is from the cache.

To quote Jesse Wilson:

There are a few combos.

.networkResponse() only – your request was served from network exclusively.

.cacheResponse() only – your request was served from cache exclusively.

.networkResponse() and .cacheResponse() – your request was a conditional GET, so headers are from the network and body is from the cache.

So for your example, the isFromCache method would look like:

boolean isFromCache(Result<?> result) {
  return result.response().raw().networkResponse() == null;
}
like image 176
Eric Cochran Avatar answered Oct 02 '22 23:10

Eric Cochran