now there is a requirement that, regardless of whether the network is available or not, load the local cache first, and if the network is available and request network data, the latest data will be displayed if it is returned successfully. This improves the user experience so that the page of the poor network is not blank. However, the framework of retrofit does not seem to be implemented. It implements custom caching by adding interceptors. One request returns either cached data or network data, but not both
./**
*
*/
private static final Interceptor cacheControlInterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (!NetWorkUtils.isNetworkAvailable(GApp.getInstance())) {
request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
Log.i("ww", "no network");
}
Response response = chain.proceed(request);
if (NetWorkUtils.isNetworkAvailable(GApp.getInstance())) {
// String cacheControl = request.cacheControl().toString();
return response.newBuilder()
.header("Cache-Control", CACHE_CONTROL_NETWORK)
.removeHeader("Pragma")
.build();
} else {
return response.newBuilder()
.header("Cache-Control", "public, " + CACHE_CONTROL_CACHE)
.removeHeader("Pragma")
.build();
}
}
};