我迁移到了分页库,而不是自定义实现。我还使用Socket.io进行实时数据提取,因此,如果有新数据,我将搜索模型的ArrayList
,进行修改,然后通知适配器已进行了更改。
我如何使用Paging Library和PositionalDataSource
做同样的事情(仅更新指定的模型)?
更新1 我找到了一种访问和编辑数据的方法,但是如何通知观察者?
工厂:
public class GroupsPositionalDataSourceFactory extends DataSource.Factory<Integer, GroupModel> {
private GroupsManager manager;
public MutableLiveData<GroupsPositionalDataSource> postLiveData;
public GroupsPositionalDataSourceFactory(InstrumentManager manager) {
this.manager = manager;
}
@Override
public DataSource<Integer, GroupModel> create() {
GroupsPositionalDataSource dataSource = new GroupsPositionalDataSource(this.manager);
postLiveData = new MutableLiveData<>();
postLiveData.postValue(dataSource);
return dataSource;
}
}
数据源:
public class GroupsPositionalDataSource extends PositionalDataSource<GroupModel> {
private static final String TAG = GroupsPositionalDataSource.class.getSimpleName();
private GroupsManager manager;
public GroupsPositionalDataSource(GroupsManager manager) {
this.manager = manager;
}
private int computeCount() {
return manager.getGroupsCount(); // Do HTTP get request
}
private List<GroupModel> loadRangeInternal(int startPosition, int loadCount) {
List<GroupModel> modelList = manager.getGroupsSync(startPosition, loadCount); // Do HTTP get request
return modelList;
}
@Override
public void loadInitial(@NonNull LoadInitialParams params,
@NonNull LoadInitialCallback<GroupModel> callback) {
int totalCount = computeCount();
int position = computeInitialLoadPosition(params, totalCount);
int loadSize = computeInitialLoadSize(params, position, totalCount);
callback.onResult(loadRangeInternal(position, loadSize), position, totalCount);
}
@Override
public void loadRange(@NonNull LoadRangeParams params,
@NonNull LoadRangeCallback<GroupModel> callback) {
callback.onResult(loadRangeInternal(params.startPosition, params.loadSize));
}
}
片段初始化:
private GroupsListAdapter mGroupsListAdapter;
private GroupsPositionalDataSourceFactory factory;
LiveData<PagedList<GroupModel>> groups;
mGroupsListAdapter = new GroupsListAdapter();
mRecycler.setAdapter(mGroupsListAdapter);
PagedList.Config config = new PagedList.Config.Builder()
.setPageSize(10)
.setInitialLoadSizeHint(10)
.build();
factory = new GroupsPositionalDataSourceFactory(groupsManager);
groups = new LivePagedListBuilder(factory, config).build();
groups.observe(this, groupModels -> {
mGroupsListAdapter.submitList(groupModels);
});
在收到更新的同时更新值:
PagedList<GroupModel> pagedList = groups.getValue();
for (GroupModel model : pagedList.snapshot()) {
if (model != null) {
// Update values
// TODO: Inform the observer
}
}