如何解决ViewModel 实现 Room 缓存观察分页列表,recyclerView 中没有显示数据
我正在尝试在我的应用程序中的 recyclerView 中实现本地房间缓存。 这是视图模型类:
public class FeedDetailViewModel extends AbsViewModel<Comment> {
private long itemId;
private volatile boolean witchCache = true;
private MutableLiveData<PagedList<Comment>> cacheLiveData = new MutableLiveData<>();
private AtomicBoolean loadAfter = new AtomicBoolean(false);
@Override
public DataSource createDataSource() { return new CommentDataSource();};
public MutableLiveData<PagedList<Comment>> getcacheLiveData() {
return cacheLiveData;
}
...
private void loadData(Integer key,int requestedLoadSize,ItemKeyedDataSource.LoadCallback<Comment>
callback) {
if (key > 0) {
loadAfter.set(true);
}
Request request= ApiService.get("/comment/queryFeedComments")
.addParam("id",key)
.addParam("itemId",itemId)
.addParam("userId",UserManager.get().getUserId())
.addParam("pageCount",requestedLoadSize)
.responseType(new TypeReference<ArrayList<Comment>>() {
}.getType());
if (witchCache) {
request.cacheStrategy(Request.CACHE_ONLY);
request.execute(new JsonCallback<List<Comment>>() {
@Override
public void onCacheSuccess(ApiResponse<List<Comment>> response) {
Log.e("loadData","onCacheSuccess: ");
MutablePageKeyedDataSource dataSource = new MutablePageKeyedDataSource<Comment>();
dataSource.data.addAll(response.body);//**without network,data retrieved from cache successfully**
PagedList pagedList = dataSource.buildNewPagedList(config);
cacheLiveData.postValue(pagedList);
}
});
}
try {
Request netRequest = witchCache ? request.clone() : request;
netRequest.cacheStrategy(key == 0 ? Request.NET_CACHE : Request.NET_ONLY);
ApiResponse<List<Comment>> response = netRequest.execute();
List<Comment> data = response.body == null ? Collections.emptyList() : response.body;
callback.onResult(data);
if (key > 0) {
((MutableLiveData) getBoundaryPageData()).postValue(data.size() > 0);
loadAfter.set(false);
}
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
};
}
...
}
这是初始化适配器的代码,它扩展了 AbsPagedListAdapter:
listAdapter = new FeedCommentAdapter(mActivity) {
@Override
public void onCurrentListChanged(@Nullable PagedList<Comment> previousList,@Nullable PagedList<Comment> currentList) {
boolean empty = currentList.size() <= 0;
handleEmpty(!empty);
}
};
mRecyclerView.setAdapter(listAdapter);
这是观察分页列表变化的代码:
viewModel.setItemId(mFeed.itemId);
viewModel.getcacheLiveData().observe(mActivity,new Observer< PagedList<Comment>>() {
@Override
public void onChanged(PagedList<Comment> comments) {
listAdapter.submitList(comments);
handleEmpty(comments.size() > 0);
}
});
在观察中使用 getPagedData() 而不是 getcacheLiveData() 可以处理在网络可用的 recyclerView 中显示的数据。使用getcacheLiveData(),recyclerView中什么也没有出现,但是dataSource似乎成功接收到了从Room缓存中检索到的数据。
在我看来,代码观察分页列表的变化有问题,但我花了一些时间,因为我基本上处于初学者水平,无法弄清楚。如果有人能提供帮助,我们将不胜感激。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。