Recenlty i migrated to Paging Library instead of custom implementation. I also used Socket.io for real time data fetch, so if new data comes, i search the ArrayList of models, modify and then notify adapter that changes has been made.
How i can do the same (update only specified models) with Paging Library and PositionalDataSource?
Update 1 I found a way to access and edit data, but how to inform observers?
Factory:
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;
}
}
Data source:
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));
}
}
Init in fragment:
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);
});
While update received update the values:
PagedList<GroupModel> pagedList = groups.getValue();
for (GroupModel model : pagedList.snapshot()) {
if (model != null) {
// Update values
// TODO: Inform the observer
}
}