Ide*_*dee 9 android android-architecture-components android-paging
新的分页库的所有示例都使用了Room库,Room为我们创建了一个数据源.在我自己的情况下,我需要创建我的自定义数据源.
这是我的视图模型类中应该返回实时数据的方法.我的liveata总是返回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;
}
Run Code Online (Sandbox Code Playgroud)
这是Data类
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我认为这可以提供帮助:
1.countItems()应返回DataSource.COUNT_UNDEFINED
2. loadRange(int startPosition,int count):您可以直接执行查询.
所以现在你可以删除结果全局变量
另外,关闭占位符:
listLiveData = p.create(0,new PagedList.Config.Builder()
.setPageSize(5) //number of items loaded at once
.setPrefetchDistance(10) //Must be >0 since placeholders are off
.setEnablePlaceholders(false)
.build());
Run Code Online (Sandbox Code Playgroud)
以下是Data Class的更新代码:
public class DataClass extends TiledDataSource<ApiResult> {
@Override
public int countItems() {
return DataSource.COUNT_UNDEFINED;
}
@Override
public List<ApiResult> loadRange(int startPosition, int count) {
Call<String> call = NetworkModule.providesWebService().makeRequest();
Response<String> response = call.execute();
return parseJson(response.body());
}
Run Code Online (Sandbox Code Playgroud)
您可以在此处查看示例项目:https: //github.com/brainail/.samples/tree/master/ArchPagingLibraryWithNetwork
| 归档时间: |
|
| 查看次数: |
3484 次 |
| 最近记录: |