Paging3 简介
Paging3 能干嘛?
- 先来看看 Google 官方的描述
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 带来的好处?
- 还是直接看 Google 官方的描述
- 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
RecyclerViewadapters 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
LiveDataand RxJava.
- Built-in support for error handling, including refresh and retry capabilities.
- 即
Paging3可以自动帮我们缓存我们的页面数据,还支持自动删除重复数据,并且与RecyclerView完美适配,还提供了Kotlin的协程支持,对于请求时的 错误、刷新、重试,也都有内置支持
- 基本上,在开发过程中需要的功能和场景,
Paging3都做了相应的适配和支持
使用 Paging3 之后的程序架构

- 三个组成部分的作用:
Repository层:主要包含PagingSource及RemoteMediatorPagingSource:数据来源,数据来源可以是网络请求、本地数据库等RemoteMediator:当PagingSource的数据被加载完了(加载到最后一个了),Pager就会调用RemoteMediator的load()方法,来使RemoteMediator从 网络 上加载更多的数据,并将其缓存到本地数据库中,最后,原来的PagingSource就会调用invalidate()来标明自己已经失效,然后Pager就会接收到信息,重新创建一个PagingSource来从本地数据库中加载数据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 中使用

推荐/参考
- Author:CoderWdd
- URL:https://www.wuinsights.top//article/1424659d2a52
- Copyright:All articles in this blog, except for special statements, adopt BY-NC-SA agreement. Please indicate the source!
Relate Posts



