All examples of the new paging library have been with Room library and Room creates a Data Source for us. In my own case, I need to create my custom data source.
Here is a method in my view model class that ought to return the live data. My livedata always returns null.
LiveData<PagedList<ApiResult>> getData(){
LivePagedListProvider<Integer,ApiResult> p = new LivePagedListProvider<Integer, ApiResult>() {
@Override
protected DataSource<Integer, ApiResult> createDataSource() {
return new DataClass();
}
};
listLiveData = p.create(0,new PagedList.Config.Builder()
.setPageSize(5) //number of items loaded at once
.setPrefetchDistance(0)// the distance to the end of already loaded list before new data is loaded
.build());
return listLiveData;
}
And here is the Data class
public class DataClass extends TiledDataSource<ApiResult> {
private List<ApiResult> result = new ArrayList<>();
@Override
public int countItems() {
return result.size();
}
@Override
public List<ApiResult> loadRange(int startPosition, int count) {
Call<String> call = NetworkModule.providesWebService().makeRequest();
call.enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
Log.i(DataClass.this.getClass().getSimpleName() + " - onResponse", String.valueOf(response));
result = parseJson(response.body());
}
@Override
public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
Log.i(DataClass.this.getClass().getSimpleName() + " - onFailure", t.getMessage());
}
});
return result;
}
}