Android Jetpack系列--6. Paging3使用詳解

定義

  • Google 推出的一個應用于 Android 平臺的分頁加載庫;
  • Paging3和之前版本相差很多,完全可以當成一個新庫去學習
  • 之前我們使用ListView和RecyclerView實現分頁功能并不難,那么為啥需要paging3呢?
  • 它提供了一套非常合理的分頁架構,我們只需要按照它提供的架構去編寫業務邏輯,就可以輕松實現分頁功能;
  • 關聯知識點:協程、Flow、MVVM、RecyclerView、DiffUtil

優點

  1. 使用內存緩存數據;
  2. 內置請求去重,更有效率的顯示數據;
  3. RecyclerView自動加載更多
  4. 支持Kotlin的協程和Flow,以及LiveData和RxJava2
  5. 內置狀態處理:刷新,錯誤,加載等

使用流程如下:

需求:
  • 展示GitHub上所有Android相關的開源庫,以Star數量排序,每頁返回5條數據;
1. 引入依賴
//paging3
implementation 'androidx.paging:paging-runtime-ktx:3.0.0-beta03'
// 用于測試
testImplementation "androidx.paging:paging-common-ktx:3.0.0-beta03"
// [可選] RxJava 支持
implementation "androidx.paging:paging-rxjava2-ktx:3.0.0-beta03"
//retrofit網絡請求庫
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
//下拉刷新
implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'
2. 創建數據模型類 RepoResponse
class RepoResponse {
    @SerializedName("items") val items:List<Repo> = emptyList()
}
data class Repo(
    @SerializedName("id") val id: Int,
    @SerializedName("name") val name: String,
    @SerializedName("description") val description: String,
    @SerializedName("stargazers_count") val starCount: String,
)
3. 定義網絡請求接口 ApiService
interface ApiService {
    @GET("search/repositories?sort=stars&q=Android")
    suspend fun searRepos(@Query("page") page: Int, @Query("per_page") perPage: Int): RepoResponse

    companion object {
        private const val BASE_URL = "https://api.github.com/"
        fun create(): ApiService {
            return Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(ApiService::class.java)
        }
    }
}
4. 配置數據源
  • 自定義一個子類繼承PagingSource,然后重寫 load() 函數,并在這里提供對應當前頁數的數據, 這一步才真正用到了Paging3
  • PagingSource的兩個泛型參數,一個是頁數類型,一個是數據item類型
class RepoPagingSource(private val apiService: ApiService) : PagingSource<Int, Repo>() {
    override fun getRefreshKey(state: PagingState<Int, Repo>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Repo> {
        return try {
            val page = params.key ?: 1
            val pageSize = params.loadSize
            val repoResponse = apiService.searRepos(page, pageSize)
            val repoItems = repoResponse.items
            val prevKey = if (page > 1) page - 1 else null
            val nextKey = if (repoItems.isNotEmpty()) page + 1 else null
            LoadResult.Page(repoItems, prevKey, nextKey)
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }
}
5. 在ViewModel中實現接口請求
  • PagingConfig的一個參數prefetchDistance,用于表示距離底部多少條數據開始預加載,設置0則表示滑到底部才加載,默認值為分頁大??;若要讓用戶對加載無感,適當增加預取閾值即可,比如調整到分頁大小的5倍;
  • cachedIn() 是 Flow<PagingData> 的擴展方法,用于將服務器返回的數據在viewModelScope這個作用域內進行緩存,假如手機橫豎屏發生了旋轉導致Activity重新創建,Paging 3就可以直接讀取緩存中的數據,而不用重新發起網絡請求了。
//1. Repository中實現網絡請求
object Repository {
    private const val PAGE_SIZE = 5
    private val gitHubService = ApiService.create()
    fun getPagingData(): Flow<PagingData<Repo>> {
        // PagingConfig的一個參數prefetchDistance,用于表示距離底部多少條數據開始預加載,
        // 設置0則表示滑到底部才加載。默認值為分頁大小。
        // 若要讓用戶對加載無感,適當增加預取閾值即可。 比如調整到分頁大小的5倍
        return Pager(config = PagingConfig(pageSize = PAGE_SIZE, prefetchDistance = PAGE_SIZE * 5),
            pagingSourceFactory = { RepoPagingSource(gitHubService) }).flow
    }
}
//2. ViewModel中調用Repository
class Paging3ViewModel : ViewModel() {
    fun getPagingData(): Flow<PagingData<Repo>> {
        return Repository.getPagingData().cachedIn(viewModelScope)
    }
}
6. 實現RecyclerView的Adapter
  • 必須繼承 PagingDataAdapter
class RepoAdapter : PagingDataAdapter<Repo, RepoAdapter.ViewHolder>(COMPARATOR) {
    companion object {
        //因為Paging 3在內部會使用DiffUtil來管理數據變化,所以這個COMPARATOR是必須的
        private val COMPARATOR = object : DiffUtil.ItemCallback<Repo>() {
            override fun areItemsTheSame(oldItem: Repo, newItem: Repo): Boolean {
                return oldItem.id == newItem.id
            }

            override fun areContentsTheSame(oldItem: Repo, newItem: Repo): Boolean {
                return oldItem == newItem
            }
        }
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
        val binding: LayoutRepoItemBinding? =DataBindingUtil.bind(itemView)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.binding?.repo=getItem(position)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view=LayoutInflater.from(parent.context).inflate(R.layout.layout_repo_item,parent,false)
        return ViewHolder(view)
    }
}
7. FooterAdapter的實現
  • 用于實現加載更多,必須繼承自LoadStateAdapter,
  • retry():使用Kotlin的高階函數來給重試按鈕注冊點擊事件
class FooterAdapter(val retry: () -> Unit) : LoadStateAdapter<FooterAdapter.ViewHolder>() {
    class ViewHolder(val binding: ViewDataBinding) : RecyclerView.ViewHolder(binding.root)

    override fun onBindViewHolder(holder: ViewHolder, loadState: LoadState) {
        val binding=holder.binding as LayoutFooterItemBinding
        when (loadState) {
            is LoadState.Error -> {
                binding.progressBar.visibility = View.GONE
                binding.retryButton.visibility = View.VISIBLE
                binding.retryButton.text = "Load Failed, Tap Retry"
                binding.retryButton.setOnClickListener {
                    retry()
                }
            }
            is LoadState.Loading -> {
                binding.progressBar.visibility = View.VISIBLE
                binding.retryButton.visibility = View.VISIBLE
                binding.retryButton.text = "Loading"
            }
            is LoadState.NotLoading -> {
                binding.progressBar.visibility = View.GONE
                binding.retryButton.visibility = View.GONE
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, loadState: LoadState): ViewHolder {
        val binding: LayoutFooterItemBinding =
            LayoutFooterItemBinding.inflate(
                LayoutInflater.from(parent.context), parent, false
            )
        return ViewHolder(binding)
    }
}
8. 在Activity中使用
  • mAdapter.submitData()是觸發Paging 3分頁功能的核心; 它接收一個PagingData參數,這個參數我們需要調用ViewModel中返回的Flow對象的collect()函數才能獲取到,collect()函數有點類似于Rxjava中的subscribe()函數,總之就是訂閱了之后,消息就會源源不斷往這里傳。不過由于collect()函數是一個掛起函數,只有在協程作用域中才能調用它,因此這里又調用了lifecycleScope.launch()函數來啟動一個協程。
  • 加載更多:通過mAdapter.withLoadStateFooter實現;
  • 下拉刷新:這里下來刷新是配合SwipeRefreshLayout使用,在其OnRefreshListener中調用mAdapter.refresh(),并在mAdapter.addLoadStateListener中處理下拉刷新的UI邏輯;
  • 雖然有withLoadStateHeader,但它并不是用于實現刷新,而是加載上一頁,需要當前起始頁>1時才生效
class Paging3Activity : AppCompatActivity() {
    private val viewModel by lazy {
        ViewModelProvider(this).get(Paging3ViewModel::class.java)
    }
    private val mAdapter:RepoAdapter = RepoAdapter()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //在Activity中使用
        val binding: ActivityPaging3Binding =
            DataBindingUtil.setContentView(this, R.layout.activity_paging3)
        binding.lifecycleOwner = this
        //下拉刷新
        binding.refreshlayout.setOnRefreshListener {
            mAdapter.refresh()
        }
        binding.recyclerView.layoutManager = LinearLayoutManager(this)
        //添加footer
        binding.recyclerView.adapter = mAdapter.withLoadStateFooter(FooterAdapter {
            mAdapter.retry()
        })
//        binding.recyclerView.adapter = repoAdapter.withLoadStateHeaderAndFooter(
//            header = HeaderAdapter { repoAdapter.retry() },
//            footer = FooterAdapter { repoAdapter.retry() }
//        )
        lifecycleScope.launch {
            viewModel.getPagingData().collect {
                mAdapter.submitData(it)
            }
        }
        //監聽加載狀態
        mAdapter.addLoadStateListener {
            //比如處理下拉刷新邏輯
            when (it.refresh) {
                is LoadState.NotLoading -> {
                    binding.recyclerView.visibility = View.VISIBLE
                    binding.refreshlayout.isRefreshing = false
                }
                is LoadState.Loading -> {
                    binding.refreshlayout.isRefreshing = true
                    binding.recyclerView.visibility = View.VISIBLE
                }
                is LoadState.Error -> {
                    val state = it.refresh as LoadState.Error
                    binding.refreshlayout.isRefreshing = false
                    Toast.makeText(this, "Load Error: ${state.error.message}", Toast.LENGTH_SHORT)
                        .show()
                }
            }
        }
    }
}
9. RemoteMediator
RemoteMediator 和 PagingSource 的區別:
  • PagingSource:實現單一數據源以及如何從該數據源中查找數據,推薦用于加載有限的數據集(本地數據庫),例如 Room,數據源的變動會直接映射到 UI 上;
  • RemoteMediator:實現加載網絡分頁數據并更新到數據庫中,但是數據源的變動不能直接映射到 UI 上;
  • 可以使用 RemoteMediator 實現從網絡加載分頁數據更新到數據庫中,使用 PagingSource 從數據庫中查找數據并顯示在 UI 上
RemoteMediator的使用
  1. 定義數據源
// 本地數據庫存儲使用的Room,Room使用相關的之后會在另一篇文章中詳細介紹,這里直接貼代碼了
//1. 定義實體類,并添加@Entity注釋
@Entity
data class RepoEntity(
    @PrimaryKey  val id: Int,
    @ColumnInfo(name = "name")  val name: String,
    @ColumnInfo(name = "description") val description: String,
    @ColumnInfo(name = "star_count")  val starCount: String,
    @ColumnInfo(name = "page") val page: Int ,
)

//2. 定義數據訪問對象RepoDao
@Dao
interface RepoDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(pokemonList: List<RepoEntity>)

    @Query("SELECT * FROM RepoEntity")
    fun get(): PagingSource<Int, RepoEntity>

    @Query("DELETE FROM RepoEntity")
    suspend fun clear()

    @Delete
    fun delete(repo: RepoEntity)

    @Update
    fun update(repo: RepoEntity)
}

//3. 定義Database
@Database(entities = [RepoEntity::class], version = Constants.DB_VERSION)
abstract class AppDatabase : RoomDatabase() {
    abstract fun repoDao(): RepoDao

    companion object {
        val instance = AppDatabaseHolder.db
    }

    private object AppDatabaseHolder {
        val db: AppDatabase = Room
            .databaseBuilder(
                AppHelper.mContext,
                AppDatabase::class.java,
                Constants.DB_NAME
            )
            .allowMainThreadQueries() //允許在主線程中查詢
            .build()
    }
}

//4. 數據庫常量管理
interface Constants {
    /**
     * 數據庫名稱
     */
    String DB_NAME = "JetpackDemoDataBase.db";

    /**
     * 數據庫版本
     */
    int DB_VERSION = 1;
}
  1. 實現 RemoteMediator
// 1. RemoteMediator 目前是實驗性的 API ,所有實現 RemoteMediator 的類
//都需要添加 @OptIn(ExperimentalPagingApi::class) 注解,
//使用 OptIn 注解,要App的build.gradle中配置
android {
    kotlinOptions {
        freeCompilerArgs += ["-Xopt-in=kotlin.RequiresOptIn"]
    }
}

//2. 自定義RepoMediator,繼承RemoteMediator
//RemoteMediator 和 PagingSource 相似,都需要覆蓋 load() 方法,但是其參數不同
@OptIn(ExperimentalPagingApi::class)
class RepoMediator(
    val api: ApiService,
    val db: AppDatabase
) : RemoteMediator<Int, RepoEntity>() {
    override suspend fun load(
        loadType: LoadType,
        state: PagingState<Int, RepoEntity>
    ): MediatorResult {
        val repoDao = db.repoDao()
        val pageKey = when (loadType) {
            //首次訪問 或者調用 PagingDataAdapter.refresh()時
            LoadType.REFRESH -> null
            //在當前加載的數據集的開頭加載數據時
            LoadType.PREPEND -> return MediatorResult.Success(endOfPaginationReached = true)
            //下拉加載更多時
            LoadType.APPEND -> {
                val lastItem = state.lastItemOrNull()
                if (lastItem == null) {
                    return MediatorResult.Success(
                        endOfPaginationReached = true
                    )
                }
                lastItem.page
            }
        }

        //無網絡則加載本地數據
        if (!AppHelper.mContext.isConnectedNetwork()) {
            return MediatorResult.Success(endOfPaginationReached = true)
        }

        //請求網絡分頁數據
        val page = pageKey ?: 0
        val pageSize = Repository.PAGE_SIZE
        val result = api.searRepos(page, pageSize).items
        val endOfPaginationReached = result.isEmpty()
        val items = result.map {
            RepoEntity(
                id = it.id,
                name = it.name,
                description = it.description,
                starCount = it.starCount,
                page=page + 1
            )
        }

        //插入數據庫
        db.withTransaction {
            if (loadType==LoadType.REFRESH){
                repoDao.clear()
            }
            repoDao.insert(items)
        }
        return MediatorResult.Success(endOfPaginationReached = endOfPaginationReached)
    }
}
  1. 在 Repository 中構建 Pager
object Repository {
    const val PAGE_SIZE = 5
    private val gitHubService = ApiService.create()
    private val db = AppDatabase.instance
    private val pagingConfig = PagingConfig(
        // 每頁顯示的數據的大小
        pageSize = PAGE_SIZE,
        // 開啟占位符
        enablePlaceholders = true,
        // 預刷新的距離,距離最后一個 item 多遠時加載數據
        // 默認為 pageSize
        prefetchDistance = PAGE_SIZE,
        // 初始化加載數量,默認為 pageSize * 3
        initialLoadSize = PAGE_SIZE
    )

    @OptIn(ExperimentalPagingApi::class)
    fun getPagingData2(): Flow<PagingData<Repo>> {
        return Pager(
            config = pagingConfig,
            remoteMediator = RepoMediator(gitHubService, db)
        ) {
            db.repoDao().get()
        }.flow.map { pagingData ->
            pagingData.map { RepoEntity2RepoMapper().map(it) }
        }
    }
}

class RepoEntity2RepoMapper : Mapper<RepoEntity, Repo> {
    override fun map(input: RepoEntity): Repo = Repo(
        id = input.id,
        name = input.name,
        description = input.description,
        starCount = input.starCount
    )
}
  1. 在 ViewModel 獲取數據
class Paging3ViewModel : ViewModel() {
    fun getPagingData2(): LiveData<PagingData<Repo>> =
        Repository.getPagingData2().cachedIn(viewModelScope).asLiveData()
}
  1. 在Activity中注冊觀察者
 viewModel.getPagingData2().observe(this, {
            mAdapter.submitData(lifecycle, it)
        })
  • 到此打完收工,跑一下代碼,發現無網絡情況下就會加載數據庫中的數據,有網絡就會從網絡請求數據更新數據庫并刷新UI界面

我是今陽,如果想要進階和了解更多的干貨,歡迎關注微信公眾號 “今陽說” 接收我的最新文章

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容