Paging3 简介

Paging3 能干嘛?

The Paging library helps you load and display pages of data from a larger dataset from local storage or over network. This approach allows your app to use both network bandwidth and system resources more efficiently.
  • 意思就是 Paging3 其实就是一个可以用来从本地或网络上,加载和显示(大量)数据的组件

使用 Paging3 带来的好处?

  • In-memory caching for your paged data. This ensures that your app uses system resources efficiently while working with paged data.
  • Built-in request deduplication, ensuring that your app uses network bandwidth and system resources efficiently.
  • Configurable RecyclerView adapters that automatically request data as the user scrolls toward the end of the loaded data.
  • First-class support for Kotlin coroutines and Flow, as well as LiveData and RxJava.
  • Built-in support for error handling, including refresh and retry capabilities.
  • 即 Paging3 可以自动帮我们缓存我们的页面数据,还支持自动删除重复数据,并且与 RecyclerView 完美适配,还提供了 Kotlin 的协程支持,对于请求时的 错误、刷新、重试,也都有内置支持
  • 基本上,在开发过程中需要的功能和场景,Paging3 都做了相应的适配和支持

使用 Paging3 之后的程序架构

notion image
  • 三个组成部分的作用:
    • Repository 层:主要包含 PagingSource 及 RemoteMediator
      • PagingSource:数据来源,数据来源可以是网络请求、本地数据库等
      • RemoteMediator:当 PagingSource 的数据被加载完了(加载到最后一个了),Pager 就会调用 RemoteMediator 的 load() 方法,来使 RemoteMediator 从 网络 上加载更多的数据,并将其缓存到本地数据库中,最后,原来的 PagingSource 就会调用 invalidate() 来标明自己已经失效,然后 Pager 就会接收到信息,重新创建一个 PagingSource 来从本地数据库中加载数据
        • notion image
    • ViewModel 层:主要包含了 Pager,并通过 Pager 把需要加载的数据,包装成 PagingData,并以 flow 的形式返回给 UI 层
    • UI 层:主要是一个 PagingDataAdapter,其实也是一个 RecyclerViewAdapter,用于把 ViewModel 返回的 PagingData 与 RecyclerView 连接上

简单使用

接口说明

  • 接口链接:https://rickandmortyapi.com/api/character/?page=20
  • 请求方法:GET
  • 返回类型:

XML 布局

  • RecyclerViewItem
  • MainActivity:

data 类定义

引入依赖

实现PagingSource

在 ViewModel 中 定义 Pager

定义 Paging3 专为 RecyclerView 设计的 PagingDataAdapter

在 UI 中使用

notion image

推荐/参考

Architecture MVPLeetcode_200-岛屿数量