Android Jetpack 系列kotlin

Android Jetpack系列--6. Paging3使用详

2021-09-01  本文已影响0人  今阳说

定义

优点

  1. 使用内存缓存数据;
  2. 内置请求去重,更有效率的显示数据;
  3. RecyclerView自动加载更多
  4. 支持Kotlin的协程和Flow,以及LiveData和RxJava2
  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. 配置数据源
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中实现接口请求
//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
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的实现
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中使用
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 的区别:
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)
        })

我是今阳,如果想要进阶和了解更多的干货,欢迎关注微信公众号 “今阳说” 接收我的最新文章

上一篇下一篇

猜你喜欢

热点阅读