3

我正在遵循使用 LiveData 的 Android 指南: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;
}

}

谢谢

4

1 回答 1

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();
于 2018-07-06T02:06:54.387 回答