我有一个要使用分页库显示的人员列表,从本地数据库加载初始数据,一旦需要更多数据,我调用 API 从服务器获取并将其保存到数据库中。
我的片段:
Class PersonListFragment: Fragment(){
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
recycler_view.layoutManager = LinearLayoutManager(context)
recycler_view.adapter = personListAdapter
personListViewModel.getPersonsLiveData().observe(viewLifecycleOwner, Observer {
personListAdapter.submitList(it)
})
}
}
我的视图模型:
class PersonViewModel: ViewModel{
lateinit var personsLiveData: LiveData<PagedList<Person>>
lateinit var boundaryCallback: TransactionBoundaryCallback
fun getPersonsLiveData(): LiveData<PagedList<Person>> = personsLiveData
Init {
val dataSourceFactory = getPersons()
val config = PagedList.Config.Builder()
.setEnablePlaceholders(false)
.setPageSize(10)
.build()
boundaryCallback = PersonBoundaryCallback()
personsLiveData = LivePagedListBuilder(dataSourceFactory, config)
.setBoundaryCallback(boundaryCallback)
.build()
}
private fun getPersons(): DataSource.Factory<Int, Persons> = personDAO.getAllPersons()
}
列表适配器:
class PersonListAdapter: PagedListAdapter<Person, PersonListAdapter.PersonViewHolder>(DIFF_CALLBACK) {
...
companion object {
val DIFF_CALLBACK: DiffUtil.ItemCallback<Person> = object : DiffUtil.ItemCallback<Person>() {
override fun areItemsTheSame(oldItem: Person, newItem: Person): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Person, newItem: Person): Boolean {
return oldItem == newItem
}
}
}
}
道:
@Dao
interface PersonDAO {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(persons: List<Person>): Completable
@androidx.room.Persons
@Query("Select * from person_table")
fun getAllPersons(): DataSource.Factory<Int, Person>
}
回调类:
class PersonBoundaryCallback: PagedList.BoundaryCallback<Person>(){
override fun onZeroItemsLoaded() {
requestAndSave()
super.onZeroItemsLoaded()
}
override fun onItemAtEndLoaded(itemAtEnd: Person) {
...
//request data from API and saves it into DB
requestAndSave()
super.onItemAtEndLoaded(itemAtEnd)
}
}
直到这里一切都好(获取的数据保存到 db 中),但是 recyclerview 不会用新数据更新列表,而是只显示初始数据
我已经搜索了这个主题并对其进行了调整,但到目前为止找不到为什么不适合我。