我正在遵循使用 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;
}
}
谢谢