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

标签 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;
}

谢谢

最佳答案

这应该有助于改造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/

相关文章:

android - 将陀螺仪与加速度计相结合以获得航向

java - 错误: Multiple annotations found at this line:

android - 将图像的特定部分制作成 Android 应用程序的可点击按钮

javascript - window.location.href 仅在 IE 上清除浏览器缓存后才起作用

caching - 在数据库和 redis 缓存之间同步数据的最佳策略是什么

android - RxJava 和 Observable 改造 API 调用

android - 通过改造处理Rxjava中的无网络

android - PlayStore 应用程序未在 Android 平板电脑中显示

asp.net - .NET 4.0 ObjectCache 的线程安全和范围管理

android - 使用新的 Google 的 Jetpack 组件的最低 Android API 级别是多少