如何使用列表大小与Room数据库返回的列表大小不同的AAC分页库

Mat*_*óes 8 android android-room android-architecture-components android-paging

我正在尝试使用new Paging LibraryRoomas数据库,但遇到了一个问题,PagedList数据库返回的列表与发送到UI的列表不应该相同,map在显示给用户之前以及执行此map操作期间,我需要一些实体我更改列表大小(添加项目),显然Paging Library不支持这种操作,因为当我尝试运行应用程序时,出现以下异常:

Caused by: java.lang.IllegalStateException: Invalid Function 'function_name' changed return size. This is not supported.
Run Code Online (Sandbox Code Playgroud)

查看分页库源代码,您会看到以下方法:

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;
}
Run Code Online (Sandbox Code Playgroud)

PagedList在使用动态项目添加动态项目之前,是否有解决方法或要解决的问题?

这就是我在做的

@Query("SELECT * FROM table_name")
fun getItems(): DataSource.Factory<Int, Item>
Run Code Online (Sandbox Code Playgroud)

LocalSource

fun getItems(): DataSource.Factory<Int, Item> {
    return database.dao().getItems()
        .mapByPage { map(it) } // This map operation changes the list size
}
Run Code Online (Sandbox Code Playgroud)

Pha*_*inh 0

我面临同样的问题,仍在寻找更好的解决方案。
就我而言,我必须在每个用户从 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
    }
}
Run Code Online (Sandbox Code Playgroud)

我当前的用户类别

data class User(
    @SerializedName("login")
    val login: String,
    @SerializedName("id")
    val id: Long = 0,
    @SerializedName("avatar_url")
    val avatarUrl: String
) {
    constructor() : this("", 0, "")
}
Run Code Online (Sandbox Code Playgroud)

当然,要显示Section,我将有另一种方法而不将其添加到RecyclerView data list(例如仅使用位置),但在我的情况下,用户可以从列表中删除项目,因此使用位置可能很难处理

实际上,我回滚以使用旧的加载更多方式(使用EndlessRecyclerViewScrollListener)但希望它有帮助