如何使用LiveData + Retrofit在30分钟内缓存数据?

时间:2018-07-05 19:14:16

标签: android caching android-livedata mutablelivedata

我遵循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;
}

}

谢谢

1 个答案:

答案 0 :(得分:0)

这应该有助于翻新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();