-
-
Save 0xSG/6de5f5c03a44a8f3dbb5e2e910fe8bfb to your computer and use it in GitHub Desktop.
How to force a cached or network response on Android with Retrofit + OkHttp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
OkHttpClient okHttpClient = new OkHttpClient(); | |
try { | |
int cacheSize = 10 * 1024 * 1024 // 10 MiB | |
Cache cache = new Cache(getCacheDir(), cacheSize); | |
okHttpClient.setCache(cache); | |
} catch (IOException e) { | |
Log.e(TAG, "Could not set cache", e); | |
} | |
// Forces cache. Used for cache connection | |
RequestInterceptor cacheInterceptor = new RequestInterceptor() { | |
@Override | |
public void intercept(RequestFacade request) { | |
request.addHeader("Cache-Control", "only-if-cached, max-stale=" + Integer.MAX_VALUE); | |
} | |
}; | |
// Skips cache and forces full refresh. Used for service connection | |
RequestInterceptor noCacheInterceptor = new RequestInterceptor() { | |
@Override | |
public void intercept(RequestFacade request) { | |
request.addHeader("Cache-Control", "no-cache"); | |
} | |
}; | |
// Build service connections | |
RestAdapter.Builder builder = new RestAdapter.Builder() | |
.setEndpoint("http://yourserviceurl.com") | |
.setClient(new OkClient(okHttpClient)) | |
// process request in the order they are called (e.g. cache first then service) | |
.setExecutors(Executors.newSingleThreadExecutor(), new MainThreadExecutor()); | |
.setRequestInterceptor(noCacheInterceptor) | |
ServiceConnection serviceConnection = builder.build().create(ServiceConnection.class); | |
builder.setRequestInterceptor(cacheInterceptor); | |
ServiceConnection cacheConnection = builder.build().create(ServiceConnection.class); | |
/* | |
Now you can use the cacheConnection to show the user cached results immediately and | |
then try to receive network results using the serviceConnection. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment