问题描述
我有一个显示搜索项目列表的搜索片段。 如果用户键入内容,我将该字符串作为新查询参数传递给 url,并使用分页 3 库获取新列表。
//viewmodel
lateinit var postListUrl: String
val postList: Flow<PagingData<Post>> = Pager(PagingConfig(pageSize = 20)) {
PostPagingSource(postRepository,postListUrl)
}.flow.cachedIn(viewmodelScope)
//fragment
fun showPostList(url: String) {
postlistadapter.submitData(lifecycle,PagingData.empty())
viewmodel.postListUrl = url
viewLifecycleOwner.lifecycleScope.launch {
viewmodel.postList.collectLatest {
postlistadapter.submitData(it)
}
}
}
通过更改 url (showPostList(newUrl)
,列表保持不变。可能在 viewmodel 中使用缓存列表。
另一个解决方案是:
在片段的 showPostList(initUrl)
中使用 onViewCreated
,然后通过更改参数使用 blew 方法:
//fragment
fun changePostList(url: String) {
viewmodel.postListUrl = url
postlistadapter.refresh()
}
这项工作,但如果旧列表和新列表有共同的项目,新列表显示在最后一个共同的可见项目上。 例如,如果旧列表的第 5 个位置项与新列表的第 7 个相同,则在列表更改以显示新列表后,它从第 7 个位置而不是第一个项目开始。
//viewmodel
val postListUrlFlow = MutableStateFlow("")
val postList = postListUrlFlow.flatMapLatest { query ->
Pager(PagingConfig(pageSize = 20)) {
PostPagingSource(postRepository,query)
}.flow.cachedIn(viewmodelScope)
}
//fragment
fun showPostList(url: String) {
postlistadapter.submitData(lifecycle,PagingData.empty())
viewmodel.postListUrlFlow.value = url
viewLifecycleOwner.lifecycleScope.launch {
viewmodel.postList.collectLatest {
postlistadapter.submitData(it)
}
}
}
但是通过使用此列表刷新返回片段,有时会更改 Recyclerview
状态。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)