我正在按照 Android 指南使用 LiveData:https://developer.android.com/jetpack/docs/guide ,我可以调用电话并取回对象列表,但我不明白如何缓存该对象列表,在这个例子中我不太确定类 UserCache 是如何定义的,而且我不知道如何添加缓存时间。
你能告诉我怎么做吗?
这是类:
@Singleton
public class UserRepository {
private Webservice webservice;
private UserCache userCache;
public LiveData<User> getUser(String userId) {
LiveData<User> cached = userCache.get(userId);
if (cached != null) {
return cached;
}
final MutableLiveData<User> data = new MutableLiveData<>();
userCache.put(userId, data);
// this is still suboptimal but better than before.
// a complete implementation must also handle the error cases.
webservice.getUser(userId).enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
data.setValue(response.body());
}
});
return data;
}
谢谢
最佳答案
这应该有助于改造2
OkHttpClient okHttpClient = new OkHttpClient()
.newBuilder()
.cache(new Cache(WaterGate.getAppContext().getCacheDir(), 10 * 1024 *1024))
.addInterceptor(chain -> {
Request request = chain.request();
if (NetworkUtil.isDeviceConnectedToInternet(WaterGate.getAppContext())) {
request = request.newBuilder().header("Cache-Control", "public, max-age=" + 60).build();
} else {
request = request.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + 60 * 60 * 24 * 7).build();
}
return chain.proceed(request);
})
.build();
Retrofit.Builder()
.client(okHttpClient)
.build();
关于android - 如何使用 LiveData + Retrofit 缓存 30 分钟内的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51198413/