Android Paging+BoundaryCallback分頁的實現(xiàn)與封裝

ViewModel+LiveData Android Architecture Components
Paging Library Paging

Paging

1. Datasource

數(shù)據(jù)源抽象類,Paging有三種實現(xiàn)
(1)PageKeyedDataSource 按頁加載,如請求數(shù)據(jù)時傳入page頁碼。
(2)ItemKeyedDataSource 按條目加載,即請求數(shù)據(jù)需要傳入其它item的信息,如加載第n+1項的數(shù)據(jù)需傳入第n項的id。
(3)PositionalDataSource 按位置加載,如加載指定從第n條到n+20條。

2. PagedList

PagedList是List的子類,通過Datasource加載數(shù)據(jù),并可以設置一次加載的數(shù)量以及預加載的數(shù)量等。

3.PagedListAdapter

PagedListAdapte是RecyclerView.Adapter的實現(xiàn),用于展示PagedList的數(shù)據(jù)。數(shù)據(jù)源變動時后臺線程通過DiffUtil比較前后兩個PagedList的差異,然后調用notifyItem...()方法更新RecyclerView。

4. LivePagedListBuilder

將PagedList和LiveData整合成LiveData<PagedList>。

Paging+BoundaryCallback封裝

網(wǎng)上許多demo都是基于google example,官方example主要是教我們怎么用,也有很多值得參考的地方,但直接搬項目中去用卻明顯水土不服,建議先理解了google example中Paging的用法,再自己封裝下...

定義列表的幾種狀態(tài)
/**
 * 列表狀態(tài)
 */
sealed class ListStatus

/**
 * 初始化中
 */
class Initialize : ListStatus()

/**
 * 初始化成功
 */
class InitializeSuccess : ListStatus()

/**
 * 初始化錯誤
 */
class InitializeError : ListStatus()

/**
 * 列表空
 */
class Empty : ListStatus()

/**
 * 列表往下加載更多中
 */
class LoadMoreIn : ListStatus()

/**
 * 列表往下加載成功
 */
class LoadMoreSuccess : ListStatus()

/**
 * 列表往下加載失敗
 */
class LoadMoreError : ListStatus()

/**
 * 列表往下已全部加載完畢
 */
class End : ListStatus()

/**
 * 列表往上加載更多中
 */
class AtFrontLoadMoreIn : ListStatus()

/**
 * 列表往上加載成功
 */
class AtFrontLoadMoreSuccess : ListStatus()

/**
 * 列表往上加載失敗
 */
class AtFrontLoadMoreError : ListStatus()

/**
 * 列表往上已全部加載完畢
 */
class AtFrontEnd : ListStatus()
自定義BoundaryCallback
class ListBoundaryCallback<Value>(private val listLiveData: MutableLiveData<ListStatus>) : PagedList.BoundaryCallback<Value>() {
    override fun onZeroItemsLoaded() {
        super.onZeroItemsLoaded()
        listLiveData.value = Empty()
    }

    override fun onItemAtEndLoaded(itemAtEnd: Value) {
        super.onItemAtEndLoaded(itemAtEnd)
        listLiveData.value = End()
    }

    override fun onItemAtFrontLoaded(itemAtFront: Value) {
        super.onItemAtFrontLoaded(itemAtFront)
        listLiveData.value = AtFrontEnd()
    }
}

BoundaryCallbackDatasource中的數(shù)據(jù)加載到邊界時的回調,為PagedList設置BoundaryCallback用來監(jiān)聽加載本地數(shù)據(jù)的事件,對應回調方法中為ListStatus設置不同狀態(tài)

公共ViewModel
open class MyAndroidViewModel(application: Application) : AndroidViewModel(application) {
    private fun makePagedListConfig(pageSize: Int = 20): PagedList.Config =
            PagedList.Config.Builder().apply {
                setPageSize(pageSize)
                setInitialLoadSizeHint(pageSize)
                setPrefetchDistance(2)
                setEnablePlaceholders(false)
            }.build()

    fun <Key, Value> makePagedList(dataSourceFactory: DataSource.Factory<Key, Value>,
                                   listStatus: MutableLiveData<ListStatus>, pageSize: Int = 20): LiveData<PagedList<Value>> =
            LivePagedListBuilder<Key, Value>(dataSourceFactory, makePagedListConfig(pageSize))
                    .setBoundaryCallback(ListBoundaryCallback(listStatus))
                    .build()
}

ViewModel中設置PagedList.Config,初始化LivePagedListBuilder

自定義PageKeyedDataSource及相關回調
abstract class ListStatusPageKeyedDataSource<Key, Value>(private val status: MutableLiveData<ListStatus>) : PageKeyedDataSource<Key, Value>() {

    final override fun loadInitial(params: LoadInitialParams<Key>, callback: LoadInitialCallback<Key, Value>) {
        status.postValue(Initialize())
        onLoadInitial(params, ListStatusPageKeyedLoadInitialCallback(callback, status))
    }

    abstract fun onLoadInitial(params: LoadInitialParams<Key>, callback: ListStatusPageKeyedLoadInitialCallback<Key, Value>)

    final override fun loadAfter(params: LoadParams<Key>, callback: LoadCallback<Key, Value>) {
        status.postValue(LoadMoreIn())
        onLoadAfter(params, ListStatusPageKeyedLoadCallback(callback, status))
    }

    abstract fun onLoadAfter(params: LoadParams<Key>, callback: ListStatusPageKeyedLoadCallback<Key, Value>)

    final override fun loadBefore(params: LoadParams<Key>, callback: LoadCallback<Key, Value>) {
        status.postValue(AtFrontLoadMoreIn())
        onLoadBefore(params, ListStatusAtFrontPageKeyedLoadCallback(callback, status))
    }

    abstract fun onLoadBefore(params: LoadParams<Key>, callback: ListStatusAtFrontPageKeyedLoadCallback<Key, Value>)
}

PageKeyedDataSource是數(shù)據(jù)源, 將這幾種回調替換成我們自定義的回調并抽象出來,改變對應Status狀態(tài)。

class ListStatusPageKeyedLoadInitialCallback<Key, Value>(
        private val callback: PageKeyedDataSource.LoadInitialCallback<Key, Value>,
        private val listStatus: MutableLiveData<ListStatus>) : PageKeyedDataSource.LoadInitialCallback<Key, Value>() {

    override fun onResult(data: MutableList<Value>, position: Int, totalCount: Int, previousPageKey: Key?, nextPageKey: Key?) {
        callback.onResult(data, position, totalCount, previousPageKey, nextPageKey)
        if (!data.isEmpty()) {
            listStatus.postValue(InitializeSuccess())
        } else {
            // 當列表為空時 BoundaryCallback 會回調 Empty 狀態(tài)因此這里不用處理
        }
    }

    override fun onResult(data: MutableList<Value>, previousPageKey: Key?, nextPageKey: Key?) {
        callback.onResult(data, previousPageKey, nextPageKey)
        if (!data.isEmpty()) {
            listStatus.postValue(InitializeSuccess())
        } else {
            // 當列表為空時 BoundaryCallback 會回調 Empty 狀態(tài)因此這里不用處理
        }
    }

    fun onError() {
        listStatus.postValue(InitializeError())
    }
}

class ListStatusPageKeyedLoadCallback<Key, Value>(
        private val callback: PageKeyedDataSource.LoadCallback<Key, Value>,
        private val listStatus: MutableLiveData<ListStatus>) : PageKeyedDataSource.LoadCallback<Key, Value>() {

    override fun onResult(data: MutableList<Value>, adjacentPageKey: Key?) {
        callback.onResult(data, adjacentPageKey)
        listStatus.postValue(LoadMoreSuccess())
    }

    fun onError() {
        listStatus.postValue(LoadMoreError())
    }
}

class ListStatusAtFrontPageKeyedLoadCallback<Key, Value>(
        private val callback: PageKeyedDataSource.LoadCallback<Key, Value>,
        private val listStatus: MutableLiveData<ListStatus>) : PageKeyedDataSource.LoadCallback<Key, Value>() {

    override fun onResult(data: MutableList<Value>, adjacentPageKey: Key?) {
        callback.onResult(data, adjacentPageKey)
        listStatus.postValue(AtFrontLoadMoreSuccess())
    }

    fun onError() {
        listStatus.postValue(AtFrontLoadMoreError())
    }
}

這幾個回調分別對應初始化、向前加載、向后加載

為請求創(chuàng)建DataSource
class BourseListDataSource(status: MutableLiveData<ListStatus>) : ListStatusPageKeyedDataSource<Int, Bourse>(status) {
    override fun onLoadInitial(params: LoadInitialParams<Int>, callback: ListStatusPageKeyedLoadInitialCallback<Int, Bourse>) {
        RetrofitClient.getInstance().getAPI().getBourseList(0, params.requestedLoadSize).enqueue(object : Callback<HttpResponse<ListInfo<Bourse>>> {
            override fun onResponse(call: Call<HttpResponse<ListInfo<Bourse>>>?, response: Response<HttpResponse<ListInfo<Bourse>>>) {
                val httpResponse = HttpResponseProcess.responseProcess(response)
                callback.onResult(httpResponse.data?.list
                        ?: emptyList<Bourse>().toMutableList(), null, 1)
            }

            override fun onFailure(call: Call<HttpResponse<ListInfo<Bourse>>>?, throwable: Throwable) {
                val errorResponse = HttpResponseProcess.responseProcess<ListInfo<Bourse>>(throwable)
                callback.onError()
            }
        })
    }

    override fun onLoadAfter(params: LoadParams<Int>, callback: ListStatusPageKeyedLoadCallback<Int, Bourse>) {
        RetrofitClient.getInstance().getAPI().getBourseList(params.key * params.requestedLoadSize, params.requestedLoadSize).enqueue(object : Callback<HttpResponse<ListInfo<Bourse>>> {
            override fun onResponse(call: Call<HttpResponse<ListInfo<Bourse>>>?, response: Response<HttpResponse<ListInfo<Bourse>>>) {
                val httpResponse = HttpResponseProcess.responseProcess(response)
                callback.onResult(httpResponse.data?.list
                        ?: emptyList<Bourse>().toMutableList(), params.key + 1)
            }

            override fun onFailure(call: Call<HttpResponse<ListInfo<Bourse>>>?, throwable: Throwable) {
                val errorResponse = HttpResponseProcess.responseProcess<ListInfo<Bourse>>(throwable)
                callback.onError()
            }
        })
    }

    override fun onLoadBefore(params: LoadParams<Int>, callback: ListStatusAtFrontPageKeyedLoadCallback<Int, Bourse>) {

    }

    class Factory(private val status: MutableLiveData<ListStatus>) : DataSource.Factory<Int, Bourse>() {
        override fun create(): DataSource<Int, Bourse> = BourseListDataSource(status)
    }
    
}
 @FormUrlEncoded
 @POST("market/getBourseList")
 fun getBourseList(@Field("start") start: Int, @Field("size") size: Int): Call<HttpResponse<ListInfo<Bourse>>>

接口的DataSource中各回調直接通過Retrofit聯(lián)網(wǎng)請求數(shù)據(jù)(沒有數(shù)據(jù)持久化需求),getBourseList api需傳的參數(shù)為起始位置start與數(shù)量size, params.requestedLoadSize就是前面PagedList.Config中所配置PageSize
onLoadInitial中傳的start為0
onLoadAfter 中傳的start為params.key * params.requestedLoadSize(頁碼乘每頁數(shù)量,如果api分頁需要的是頁碼,直接傳params.key就可以)
onLoadBeforeonLoadAfter一樣,不需要向上加載的話就置空
請求成功后將數(shù)據(jù)及下一頁頁碼傳給callback的onResult,請求失敗直接調用callback的onError

為頁面創(chuàng)建ViewModel
class BourseListViewModel(application: Application) : MyAndroidViewModel(application) {
    val listStatus = MutableLiveData<ListStatus>()
    val list = makePagedList(BourseListDataSource.Factory(listStatus), listStatus)
}

ok,就這些...

頁面擴展公共方法
fun Fragment.bindList(adapter: AssemblyPagedListAdapter<Any>, hint: HintView?, listStatus: MutableLiveData<ListStatus>, list: LiveData<PagedList<Any>>, emptyFragment: Fragment? = null,
                      isFastHidden: Boolean = false, onClickListener: View.OnClickListener? = null) {
    list.observe(this, Observer { adapter.submitList(it) })

    listStatus.observe(this, Observer {
        when (it) {
            null -> adapter.loadMoreFinished(false)
            is Initialize -> hint?.loading()?.show(childFragmentManager)
            is InitializeSuccess -> if (isFastHidden) hint?.fastHidden() else hint?.hidden()
            is InitializeError -> hint?.error(onClickListener)?.show(childFragmentManager)
            is End -> adapter.loadMoreFinished(true)
            is Empty -> if (emptyFragment != null) hint?.empty(emptyFragment)?.show(childFragmentManager) else hint?.empty()?.show(childFragmentManager)
        }
    })
}

這個僅供參考,AssemblyPagedListAdapterHintView都是自定義的,大家知道什么意思就行...

頁面
class MyListFragment : BaseFragment(){
    private val viewModel by bindViewModel(BourseListViewModel::class)
    private val adapter = AssemblyPagedListAdapter<Any>().apply {
        addItemFactory(BourseItem.Factory())
        addMoreItem(LoadMoreItem.Factory())
    }
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fm_list, container, false)
    }
    override fun initViews(view: View, savedInstanceState: Bundle?) {
        recyclerView.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
        recyclerView.adapter = adapter
    }
    override fun loadData() {
        bindList(adapter, hintView, viewModel.listStatus, viewModel.list as LiveData<PagedList<Any>>)
    }
}

收工,可以看到頁面其實只需要初始化View與ViewModel,然后直接bindList就可以了

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容