1

我有这种奇怪的行为,其中 onItemAtEndLoaded 在 onZeroItemsLoaded 之后被触发,因此回收器视图继续加载并且不会停止。我在 GitHub 上有这个项目,有人可以帮帮我吗,我花了几天时间。有人可以看看吗?

https://github.com/JosePedroNobre/ProductHunter

这是我的 BoundaryCall 课程

class RepoBoundaryCallback(private val day:String,
                           private val service: PHService,
                           private val cache:PHLocalCache) : PagedList.BoundaryCallback<Post>()  {


    // keep the last requested page.
    // When the request is successful, increment the page number.
    private var lastRequestedPage = 1

    private val _networkErrors = MutableLiveData<String>()

    // LiveData of network errors.
    val networkErrors: LiveData<String>
        get() = _networkErrors

    // avoid triggering multiple requests in the same time
    private var isRequestInProgress = false

    /**
     * This method is called at the very beggining
     */
    override fun onZeroItemsLoaded() {
        requestAndSaveData()
    }

    /**
     * This method will tell when the user reached the end of the recycler view
     */
    override fun onItemAtEndLoaded(itemAtEnd: Post) {

        requestAndSaveData()
        //TODO resolver este bug
        //ele aqui sabe que chegou ao fim , o problema desta API é que nao dá o total de páginas
        // e quando ultrapassa as paginas que deve ela dá dados repetidos
        //  como o onConflit está replace ele está sempre a substituir os items e sempre a actualizar
    }

    /**
     * Requests data from the API and increment the page in case of success
     * Save the fetched data into the database to allow offline usage
     */
    private fun requestAndSaveData(){

        //TODO ao atingir o total de páginas o isRequestInProgress estará a  null(o problema de estar sempre a actualizar vem daqui)
        if (isRequestInProgress) return
        isRequestInProgress = true
        getPosts(service,day,lastRequestedPage,BuildConfig.API_KEY, NETWORK_PAGE_SIZE,{ repos ->
            cache.insert(repos){
                lastRequestedPage++
                isRequestInProgress = false
            }
        },{error ->
            _networkErrors
            isRequestInProgress = false
        })
    }

    /**
     * static block to have the page size to the network calls
     */
    companion object {
        private const val NETWORK_PAGE_SIZE = 10
    }
}

这是我的基于分页的适配器

abstract class BasePagedAdapter<T>(diffCallBack: DiffUtil.ItemCallback<T>) :  PagedListAdapter<T, RecyclerView.ViewHolder>(diffCallBack){

    @LayoutRes abstract fun layoutToInflate(viewType: Int): Int

    abstract fun defineViewHolder(viewType: Int, view: View) : RecyclerView.ViewHolder

    abstract fun doOnBindViewHolder(holder: RecyclerView.ViewHolder, item: T?, position: Int)

    final override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(layoutToInflate(viewType), parent, false)
        return defineViewHolder(viewType, view)
    }

    final override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        doOnBindViewHolder(holder, getItem(position), position)
    }

    fun retrieveItem(position: Int) = getItem(position)

}

这是我的适配器和 ViewHolder

class PostAdapter : BasePagedAdapter<Post>(diffCallBack) {

    override fun layoutToInflate(viewType: Int) = R.layout.item_post

    override fun defineViewHolder(viewType: Int, view: View) = PostViewHolder(view)

    override fun doOnBindViewHolder(holder: RecyclerView.ViewHolder, item: Post?, position: Int){
        when(holder){
            is PostViewHolder ->{
                holder.setup(item)
            }
        }
    }

    /**
     * Its the first thing to start(like a static block in java)
     */
    companion object {
        val diffCallBack = PostDiffCallback()
    }

    class PostViewHolder(view: View) : RecyclerView.ViewHolder(view){

        private var dataBindig: ItemPostBinding = DataBindingUtil.bind(view)!!

        fun setup(item: Post?){

            /**
             * Variables defined in item_post.xml
             */
            dataBindig.title = item?.productName
            dataBindig.description = item?.tagline
            dataBindig.commentCountBinding = item?.commentsCount.toString()
            dataBindig.upvotes = item?.votesCount.toString()
            dataBindig.productImage = item?.postImage?.productLargeImgUrl
            dataBindig.userImage = item?.user?.imageUrl?.userLargeImgUrl
            dataBindig.userName = item?.user?.name



            if(diffCallBack.areContentsTheSame(item,item)){

                //TODO stop incrementing the page and stop all requests
            }

        }


    }
}
4

1 回答 1

0

由于您的网络页面大小为 10,因此如下设置 Pagelist 配置以避免无限/不必要地调用onItemAtEndLoaded方法

val config = PagedList.Config.Builder()
                .setPageSize(10)  //same as your page size
                .setInitialLoadSizeHint(10) //same as your page size
                .setEnablePlaceholders(false)
                .build()
于 2020-04-18T06:37:54.340 回答