Android compose + paging3 有个坑会导致列表瞬间无限加载下一页
从进入列表开始无限循环,测试数据少的时候发现不了,线上数据多,会瞬间爆发无数请求,特此记录,给后面的踩坑人搜索解决方案。
上代码: 平常大家使用 compose 的 LazyColumn,正常写法把,key用来优化列表
val list = listOf("1", "2", "3")
LazyColumn {
items(count = list.size,
key = { index ->
val item = list[index]
item
}) { index ->
val item = list[index]
Text(text = item)
}
}
平常这样写没问题,但是paging3这样写就会导致严重问题:列表无限加载
LazyColumn {
items(count = lazyPagingItems.itemCount,
key = { index ->
val item = lazyPagingItems[index]
item?.id.toString()
}) { index ->
val item = lazyPagingItems[index]
Text(text = item?.title.toString())
}
}
原因是 :lazyPagingItems的get方法会触发下一页,peek方法不会,就是有注释的一行
operator fun get(index: Int): T? {
pagingDataPresenter[index] // this registers the value load
return itemSnapshotList[index]
}
fun peek(index: Int): T? {
return itemSnapshotList[index]
}
在 items 里面 使用lazyPagingItems[index]没问题,因为是延迟加载,滑动到末尾才会触发下一页,但是在 key里面使用 lazyPagingItems[index]则会立即触发加载下一页。。
解决办法使用官方提供的key函数:
lazyPagingItems.itemKey()
特此记录。以警示自己和后来者!