我正在利用新的Paging库从其他API加载分页数据,但是我无法理解如何在Room中缓存后继续加载新数据.目前,我有一个PagedListAdapter,它通过使用边界回调来加载来自API的项目,然后存储在本地数据库(Room)中,这些数据通过可流动的方式发送到UI.
来自BoundaryCallback的onZeroItemsLoaded和onItemAtEndLoaded调用都按预期运行,但仅适用于初始加载.一旦数据被检索一次并存储在缓存(Room)中,我将永远不会从网络服务获得新数据 – 缓存中已有数据,并且不会触发边界回调.
如何使用分页库将项目标记为陈旧,以便每次应用程序打开时我的数据都是新鲜的?
ItemCallback.kt:
class ItemBoundaryCallback : PagedList.BoundaryCallback<Item>() { override fun onZeroItemsLoaded() { itemsFromNetwork(0) } override fun onItemAtEndLoaded(itemAtEnd: Item) { itemsFromNetwork(itemAtEnd.rank) } }
ItemRepository.kt:
fun items(): Flowable<PagedList<Item>> { return RxPagedListBuilder(database.itemDao().items(),pageSize) .setBoundaryCallback(boundaryCallback) .buildFlowable(BackpressureStrategy.LATEST) }
ItemDao.kt
@Query("SELECT * FROM item ORDER BY rank ASC") fun items(): DataSource.Factory<Int,Item>
ItemAdapter.kt
class ItemAdapter() : PagedListAdapter<Item,ItemViewHolder>(diffCallback) { companion object { private val diffCallback = object : DiffUtil.ItemCallback<Item>() { override fun areItemsTheSame(old: Item,new: Item): Boolean = old.id == new.id override fun areContentsTheSame(old: Item,new: Item): Boolean = old == new } } override fun onCreateViewHolder(parent: ViewGroup,viewType: Int): ItemViewHolder { return ItemViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.r_item,parent,false)) } override fun onBindViewHolder(viewHolder: ItemViewHolder,position: Int) { viewHolder.bind(getItem(position),clickListener) } }
ItemFragment.kt
override fun onStart() { super.onStart() itemRepository.items() .subscribe(itemAdapter::submitList) .addTo(disposables)