android - 在 submitList 之后没有得到 PagedListAdapter 的 itemCount

标签 android android-livedata android-paging

我基于 PagedListAdapter 实现了分页功能,并且我已经过检查工作正常。我尝试实现以如果 ListAdapter 项为空则显示 EmptyHolder 为特色。在调用 submitList 之后,我已经尝试基于 commitCallback 如下代码。

问题

Why has PagedListAdapter item count shows as 0 even though the response contains items? How to solve this problem?

FooDataSource

private suspend fun loadItems(beforeId: String) = withContext(Dispatchers.IO) {
    getFooUseCase(beforeId)
}

override fun loadInitial(
    params: LoadInitialParams<String>,
    callback: LoadInitialCallback<String, Foo>
) {
    launch {
        loadItems(null)
            .run {
                Timber.d("loadInitial : ${list.size}") // onResponse : 20
                callback.onResult(list, null, beforeId)
            }
    }
}

FooListFragment

observe(fooList) { items ->
    // items.size or loadedCount always 0
    fooAdapter.submitList(items) {
        //fooAdapter.itemCount, fooAdapter.currentList.size or loadedSize
        //always 0...
        if(fooAdapter.itemCount == 0) {
            //show EmptyHolder
        }
    }
}

最佳答案

PagedList.BoundaryCallback 具有用于处理空初始加载的 onZeroItemsLoaded 方法

val livedPageList = LivePagedListBuilder(sourceFactory, config)
        .setBoundaryCallback(object: PagedList.BoundaryCallback<YourItem>() {
            override fun onZeroItemsLoaded() {
                super.onZeroItemsLoaded()
                // Handle empty initial load here
            }

            override fun onItemAtEndLoaded(itemAtEnd: YourItem) {
                super.onItemAtEndLoaded(itemAtEnd)
                // Here you can listen to last item on list
            }

            override fun onItemAtFrontLoaded(itemAtFront: YourItem) {
                super.onItemAtFrontLoaded(itemAtFront)
                // Here you can listen to first item on list
            }
        })
        .build()

您可以查看完整答案here

关于android - 在 submitList 之后没有得到 PagedListAdapter 的 itemCount,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57721097/

相关文章:

java - android studio中volley库无法发送请求

android - 是否可以用房间实现实时分页(aac库)?

android - MVP 架构模式中的实时数据

android - 分页 3 : How to load list at item position or at item with specific id

java - 为什么 LiveData setValue 或 PostValue 在 View 中只触发一次 onChange?

android - 为什么我无法更新 android 中的电子邮件地址?

android - 面向 Android 11 时 SpeechRecognizer 不可用

android - 从 Java 设置层列表的单个层的大小

android - 在 Livedata 上多次调用 postValue() 将导致仅发送最后一个。有没有其他解决方案?

android - 如何通过 ViewModel 从 Fragment 观察 Repository LiveData