我正在建立使用协程在数据源中获取的项目的分页列表,也正在观察该列表以在适配器中提交它,但是当它最初加载一些数据时,它不会触发观察回调。我该怎么办?
我试图调试该东西,但我发现PagedList中的ArrayList> mCallbacks列表在尝试通知数据更改时不包含任何回调,但是我不知道该怎么做。
将从数据中获取数据源并分页。
class PagedDataSource(private val account: Account, private val getItems: GetItems): PageKeyedDataSource<Int, Item>() {
override fun loadInitial(
params: LoadInitialParams<Int>,
callback: LoadInitialCallback<Int, Transaction>
) {
GlobalScope.launch {
val startPage = 0
account.id?.let {
val items = getItems(it, startPage).body.toMutableList()
callback.onResult(items, null, 1)
}
}
}
override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, Item>) {
GlobalScope.launch {
account.id?.let {
val list = getItems(it, params.key)
val items = list.body.toMutableList()
callback.onResult(items, if (params.key >= list.totalPages) null else params.key + 1)
}
}
}
override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<Int, Item>) {
//NO NEED
}
}
片段代码:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
pagedAdapter = PagedAdapter()
vItems.layoutManager = LinearLayoutManager(context)
vItems.isNestedScrollingEnabled = false
vItems.adapter = pagedAdapter
items.observe(viewLifecycleOwner, Observer { items ->
if (items != null && items.isNotEmpty()) {
pagedAdapter.submitList(items)
} else {
vItemsTitle.visibility = View.VISIBLE
}
})
}
最后在我的视图模型中编码
init {
items = initializedPagedList()
}
private fun initializedPagedList() : LiveData<PagedList<Item>> {
val factory = object: DataSource.Factory<Int, Item>() {
override fun create(): DataSource<Int, Item> {
return PagedDataSource(account, getItems)
}
}
val config = PagedList.Config.Builder()
.setPageSize(20)
.setEnablePlaceholders(false)
.build()
return LivePagedListBuilder(factory, config).build()
}
我希望在loadInitial方法中成功调用api并触发观察回调后将获取数据。
答案 0 :(得分:0)
最后,经过研究,我找到了问题的答案。
此代码中存在问题
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
pagedAdapter = PagedAdapter()
vItems.layoutManager = LinearLayoutManager(context)
vItems.isNestedScrollingEnabled = false
vItems.adapter = pagedAdapter
items.observe(viewLifecycleOwner, Observer { items ->
if (items != null && items.isNotEmpty()) {
pagedAdapter.submitList(items)
} else {
vItemsTitle.visibility = View.VISIBLE
}
})
}
我需要将其更改为
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
pagedAdapter = PagedAdapter()
vItems.layoutManager = LinearLayoutManager(context)
vItems.isNestedScrollingEnabled = false
vItems.adapter = pagedAdapter
items.observe(viewLifecycleOwner, Observer { items ->
pagedAdapter.submitList(items)
})
}
我认为这是因为在前台的PagedList异步工作/,并且您需要提交此列表一次,然后该数据源会将更新直接发送到适配器,从而避免观察。就我而言,如果列表不为空,我将提交,但是当您在一开始创建PagedList时,它将始终为空。
祝大家好运!