【发布时间】:2018-05-12 05:08:41
【问题描述】:
我的应用正在使用 Android 的 Architecture components 库,并显示从具有无限滚动效果的分页 REST api 获取的项目列表。
我想要做的是将Paging Library 与NetworkBoundResource 结合使用,这样当用户向下滚动列表时,会从数据库中获取下一个项目并显示它们(如果存在),并且同时调用 API 来更新 DB 中的项目。
我找不到这两种模式同居的任何例子。
这是 DAO:
@Query("SELECT * FROM items ORDER BY id DESC")
LivePagedListProvider<Integer,MyItem> loadListPaginated();
这是我的NetworkBoundResource 实现:
public class PagedListNetworkBoundResource extends NetworkBoundResource<PagedList<MyItem>, List<MyItem>> {
@Override
protected void saveCallResult(@NonNull List<MyItem> items) {
// Inserting new items into DB
dao.insertAll(items);
}
@Override
protected boolean shouldFetch(@Nullable PagedList<MyItem> data) {
return true;
}
@NonNull
@Override
protected LiveData<PagedList<MyItem>> loadFromDb() {
return Transformations.switchMap(dao.loadListPaginated().create(INITIAL_LOAD_KEY, PAGE_SIZE),
new Function<PagedList<MyItem>, LiveData<List<MyItem>>>() {
@Override
public LiveData<PagedList<MyItem>> apply(final PagedList<MyItem> input) {
// Here I must load nested objects, attach them,
// and return the fully loaded items
}
});
}
@NonNull
@Override
protected LiveData<ApiResponse<List<MyItem>>> createCall() {
// I don't get the current paged list offset to perform a call to the API
return ...;
}
}
【问题讨论】:
标签: android paging android-architecture-components android-paging