【发布时间】:2018-09-19 13:43:48
【问题描述】:
因此,我使用 LiveData 和 Room 数据库在分页库中编写了一个简单的注释功能,但我没有看到它实际上对任何内容进行了分页。也许我没有正确调试以确认分页正在发生。任何建议表示赞赏。
在我的 DAO 中:
@Query("SELECT * FROM notes ORDER BY id ASC")
fun allNotes(): DataSource.Factory<Int, NoteEntity>
然后在我的NotesRepository 中,我从NoteEntity 转换为Note 以保持我的数据层实现细节和应用程序的其余部分分开(我是清洁架构的粉丝)。所以结果是DataSource.Factory<Int, Note>:
override fun allNotes(): DataSource.Factory<Int, Note> =
notesDao.allNotes().map { mapper.fromDb(it) }
在我的ViewModel 中,PAGE_SIZE 是 20:
val noteList: LiveData<PagedList<Note>> =
LivePagedListBuilder(
getNotesUseCase.allNotes(), PAGE_SIZE)
我的Note 很简单:
data class Note(
val id: Long = 0,
val text: String
)
然后我在RecyclerView 中显示注释。
我的ViewHolder 包含:
class NoteViewHolder(parent: ViewGroup) : RecyclerView.ViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.note_item, parent, false)) {
private val idView = itemView.findViewById<TextView>(R.id.noteId)
private val nameView = itemView.findViewById<TextView>(R.id.noteText)
private var note: Note? = null
/**
* Items might be null if they are not paged in yet. PagedListAdapter will re-bind the
* ViewHolder when Item is loaded.
*/
fun bindTo(note: Note?) {
this.note = note
idView.text = note?.let { it.id.toString() } ?: ""
nameView.text = note?.text ?: ""
}
}
我的Adapter 包含:
class NoteAdapter(
private val clickListener: ClickListener) : PagedListAdapter<Note, NoteViewHolder>(diffCallback) {
override fun onBindViewHolder(holder: NoteViewHolder, position: Int) {
Timber.d("Binding view holder at position $position")
val note = getItem(position)
with(holder) {
bindTo(note)
note?.let {
itemView.setOnClickListener {
clickListener(note)
}
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NoteViewHolder =
NoteViewHolder(parent)
companion object {
/**
* This diff callback informs the PagedListAdapter how to compute list differences when new
* PagedLists arrive.
*/
private val diffCallback = object : DiffUtil.ItemCallback<Note>() {
override fun areItemsTheSame(oldItem: Note, newItem: Note): Boolean =
oldItem.id == newItem.id
override fun areContentsTheSame(oldItem: Note, newItem: Note): Boolean =
oldItem == newItem
}
}
}
我的Fragment 包含:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupRecyclerView()
viewModel = ViewModelProviders.of(this, noteListViewModelFactory).get(NoteListViewModel::class.java)
viewModel.noteList.observe(this, Observer { pagedNoteList ->
pagedNoteList?.let { render(pagedNoteList) }
})
}
private fun render(pagedNoteList: PagedList<Note>) {
recyclerViewAdapter.submitList(pagedNoteList)
}
RecyclerView 中的数据加载成功,每个项目绑定的时候我都看到了调试日志。 我的理解是PagedListAdapter,我在用户滚动时使用请求新页面,并通过在后台线程上计算差异来处理新的PagedLists。
我的数据源包含 100 个项目,因此我预计页面大小为 20 时,在平均大小的手机上进行测试时会调用 5 次数据。
如何调试它以确保正确的调用次数?另外,在上面的实现中,是否默认使用其中之一(PositionalDataSource、ItemKeyedDataSource 或 PageKeyedDataSource)?
【问题讨论】:
标签: android android-architecture-components android-jetpack android-paging