我正在尝试使用新的 Paging Library
和 Room
作为数据库,但我遇到了一个问题,PagedList
返回数据库不应该是发送到 UI 的同一个列表,我在向用户显示之前 map
一些实体,在此 map
操作期间我更改了列表大小(添加项目),显然 Paging Library
不支持这种操作,因为当我尝试运行该应用程序时出现此异常:
Caused by: java.lang.IllegalStateException: Invalid Function 'function_name' changed return size. This is not supported.
查看分页库源代码你会看到这个方法:
static <A, B> List<B> convert(Function<List<A>, List<B>> function, List<A> source) {
List<B> dest = function.apply(source);
if (dest.size() != source.size()) {
throw new IllegalStateException("Invalid Function " + function
+ " changed return size. This is not supported.");
}
return dest;
}
在使用前将动态项目添加到 PagedList
时,是否有解决方法或需要处理的问题?
这就是我做的
道
@Query("SELECT * FROM table_name")
fun getItems(): DataSource.Factory<Int, Item>
本地资源
fun getItems(): DataSource.Factory<Int, Item> {
return database.dao().getItems()
.mapByPage { map(it) } // This map operation changes the list size
}
最佳答案
我遇到同样的问题,仍在寻找更好的解决方案。
就我而言,我必须在每个 用户从 API 加载 之前显示 1 部分,这是我的解决方法。
class UsersViewModel : ViewModel() {
var items: LiveData<PagedList<RecyclerItem>>
init {
...
items = LivePagedListBuilder<Long, RecyclerItem>(
sourceFactory.mapByPage { it -> mapUsersToRecyclerItem(it) }, config).build()
}
private fun mapUsersToRecyclerItem(users: MutableList<User>): List<RecyclerItem> {
val numberOfSection = 1
for (i in 0 until numberOfSection) {
users.add(0, User()) // workaround, add empty user here
}
val newList = arrayListOf<RecyclerItem>()
newList.add(SectionItem())
for (i in numberOfSection until users.size) {
val user = users[i]
newList.add(UserItem(user.login, user.avatarUrl))
}
return newList
}
}
我当前的用户类别
data class User(
@SerializedName("login")
val login: String,
@SerializedName("id")
val id: Long = 0,
@SerializedName("avatar_url")
val avatarUrl: String
) {
constructor() : this("", 0, "")
}
当然,要显示 Section
,我会有另一种方式,无需将其添加到 RecyclerView 数据列表
(例如仅使用位置),但在我的情况下,用户可以删除项目从列表中,所以使用位置可能很难处理
实际上,我回滚以使用旧的加载更多方式(使用 EndlessRecyclerViewScrollListener )但希望它有所帮助
关于android - 如何使用列表大小与 Room 数据库返回的列表大小不同的 AAC 分页库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52407806/