1.概述
The Paging Library helps you load and display small chunks of data at a time. Loading partial data on demand reduces usage of network bandwidth and system resources.
這是 Google 對於 Paging 的簡介,可以這樣理解:當進行數據查詢的時候,不會一下子把所有的數據全部加載,只會按需進行加載,對於用戶來說,一般是加載幾頁數據後,就不會再有繼續查詢的想法了。比如度娘查詢的時候,搜相應的東西后,一般只會查看幾頁,所有才會有百度的淨價排名。
Google 關於 Paging 的官方文檔:https://developer.android.google.cn/topic/libraries/architecture/paging/
2. 添加依賴
dependencies {
def paging_version = "2.1.0"
//Paging的依賴
implementation "androidx.paging:paging-runtime:$paging_version" // For Kotlin use paging-runtime-ktx
// optional - RxJava support
//Paging對RxJava2的原生支持
implementation "androidx.paging:paging-rxjava2:$paging_version" // For Kotlin use paging-rxjava2-ktx
}
3. Paging 庫的組成
Paging 主要由三部分組成:PagedList、DataSource、PagedListAdapter。
3.1 PagedList
Paging 庫的核心組件是 PagedList 類。PagedList 是一個抽象類,繼承於抽象類 AbstractList。而類 AbstractList 繼承於抽象類 AbstractCollection,並且實現接口 List,支持 List 的操作。
public abstract class PagedList<T> extends AbstractList<T> {
...
...
}
3.2 DataSource
public abstract class DataSource<Key, Value> {
...
...
}
DataSource 是一個數據源,也是一個抽象類,key-value 格式,其中 key 對應加載數據的條件信息,value 對應加載數據的實體類。不能直接繼承 DataSource 實現子類,但是 Paging 庫提供了它的三個子類:
ItemKeyedDataSource<Key, Value>:用於根據第 N-1 項加載第 N 項的數據。
PageKeyedDataSource<Key, Value>:用於目標數據根據頁信息請求數據的場景,key 是頁相關的信息。例如網絡請求數據的信息中包含 next/previous 頁數的信息。
PositionalDataSource<T>:用於目標數據總數固定,通過特定的位置加載數據,這裏 Key 是 Integer 類型的位置信息,T 即Value。
3.3 PagedListAdapter
PagedListAdapter 用於展示 PagedList 的數據,繼承於 RecyclerView.Adapter。
public abstract class PagedListAdapter<T, VH extends RecyclerView.ViewHolder>
extends RecyclerView.Adapter<VH> {
...
...
}
4. Paging 使用例子
Google 官方例子:https://github.com/android/architecture-components-samples