Android 如何使用LiveData在30分钟内缓存数据+;改造?

Android 如何使用LiveData在30分钟内缓存数据+;改造?,android,caching,android-livedata,mutablelivedata,Android,Caching,Android Livedata,Mutablelivedata,我遵循Android指南使用LiveData:,我可以打电话并获取对象列表,但我不明白如何缓存该对象列表,在这个示例中,我不确定类UserCache是如何定义的,而且,我不知道如何添加缓存时间 你能告诉我怎么做吗 这是一节课: @Singleton public class UserRepository { private Webservice webservice; private UserCache userCache; public LiveDa

我遵循Android指南使用LiveData:,我可以打电话并获取对象列表,但我不明白如何缓存该对象列表,在这个示例中,我不确定类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;
}
@Singleton
公共类用户存储库{
私有网络服务;
私有用户缓存;
公共LiveData getUser(字符串用户ID){
LiveData cached=userCache.get(userId);
如果(缓存!=null){
返回缓存;
}
最终的MutableLiveData数据=新的MutableLiveData();
put(userId,data);
//这仍然是次优,但比以前更好。
//完整的实现还必须处理错误情况。
webservice.getUser(userId).enqueue(新回调(){
@凌驾
公共void onResponse(调用、响应){
data.setValue(response.body());
}
});
返回数据;
}
}


谢谢

这将有助于改进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();

谢谢你的回答,我怎样才能在我刚刚添加的代码中添加拦截器呢?好的,我想我知道怎么做,但我真的不理解max age和max staleok的含义。我想我知道怎么做。我猜最大年龄60意味着1分钟内的所有调用都将从缓存中获取响应。max stale是什么意思?是我们把它放进缓存的时候了吗?如果总是每分钟刷新缓存,为什么要在缓存中保存一周?能够离线工作?是的。这是用于离线支持的。