0

I was reading about Volley Library using this link

It says "First, Volley checks if the request can be serviced from cache. If it can, the cached response is read, parsed, and delivered. Otherwise it is passed to the network thread."

So my question here is suppose volley hits some url and network gets down in middle then in the next request how does volley gets to know if it has to take data from cache or it needs to pass the request to the network thread ?

user3387084
  • 107
  • 1
  • 8

1 Answers1

2

When you run your app, with the 1st request to an URL, Volley also checks if the cache entry of that URL existed or not. If yes and it is valid (not expired), Volley will get from cache to response. Otherwise, it passes to network thread. When getting response data, it will parse response header to see if data can be cached or not.

Then with the 2nd request of the same URL, although network down or not, web service available or not, if the cache entry of that URL existed and valid, cached data will be used to response.

You can find more details inside CacheDispatcher.java file

...
final Request<?> request = mCacheQueue.take();
request.addMarker("cache-queue-take");

// If the request has been canceled, don't bother dispatching it.
if (request.isCanceled()) {
    request.finish("cache-discard-canceled");
    continue;
}

// Attempt to retrieve this item from cache.
Cache.Entry entry = mCache.get(request.getCacheKey());
if (entry == null) {
    request.addMarker("cache-miss");
    // Cache miss; send off to the network dispatcher.
    mNetworkQueue.put(request);
    continue;
}

// If it is completely expired, just send it to the network.
if (entry.isExpired()) {
    request.addMarker("cache-hit-expired");
    request.setCacheEntry(entry);
    mNetworkQueue.put(request);
    continue;
}

// We have a cache hit; parse its data for delivery back to the request.
request.addMarker("cache-hit");
Response<?> response = request.parseNetworkResponse(
        new NetworkResponse(entry.data, entry.responseHeaders));
request.addMarker("cache-hit-parsed");
...

and also parseCacheHeaders inside HttpHeaderParser.java file.

If web server does not support caching output, you can implement cache for Volley as my answer at the following question:

Android set up Volley to use from cache

halfer
  • 19,824
  • 17
  • 99
  • 186
BNK
  • 23,994
  • 8
  • 77
  • 87