Retrofit library with disk cache support
I am using Retrofit library from netcalls. Pretty cool. But I am missing caching support. I cannot use the cache at the HTTP level (via the Cache headers). I am currently implementing custom caching with ObjectCache , but it is so difficult. It just must be awesome to extend the current retrofit with an announcement @Cache(Expire.ONE_DAY)
.
My current code is like:
public static void getRestaurant(int restaurantId, String token, boolean forceNetwork, final Callback<Restaurant> listener) {
final String key = "getRestaurant-" + restaurantId + "-" + token;
Restaurant restaurant = (Restaurant) getCacheManager().get(key, Restaurant.class, new TypeToken<Restaurant>() {}.getType());
if (restaurant != null && !forceNetwork) {
Log.d(TAG, "Cache hit: " + key);
// Cache
listener.success(restaurant);
} else {
Log.d(TAG, "Network: " + key);
// Retrofit
getNetwork().getRestaurant(restaurantId, token, new retrofit.Callback<Response>() {
@Override
public void success(Response response, retrofit.client.Response response2) {
getCacheManager().put(key, response.result.restaurant, CacheManager.ExpiryTimes.ONE_HOUR.asSeconds(), true);
listener.success(response.result.restaurant);
}
@Override
public void failure(RetrofitError error) {
listener.failure(error.getLocalizedMessage());
}
});
}
}
Now there is just template code for each method.
Or do you know any library like Retrofit with caching support?
Thank!
source to share
You can wrap a base one Client
and use the request url as the cache key.
public class CachingClient implements Client {
private final Client delegate;
@Override public Response execute(Request request) {
if (!"GET".equals(request.method())) {
return delegate.execute(request);
}
String url = request.url();
// TODO look up 'url' in your cache.
if (cacheHit) {
return createResponse(cacheResult);
}
// Cache miss! Execute with the real HTTP client.
Response response = delegate.execute(request);
// TODO cache 'response' in your cache with the 'url' key.
return response;
}
}
With Retrofit v2, we hope to include this kind of functionality with interceptors, which will not only give you a hook in the request and response chain, but also allow you to search for custom annotation, for example @Cache
.
source to share