Android Paging 3 库:如何使用新参数更改列表?

Had*_*adi 10 android android-paging kotlin-flow android-paging-3

我有一个显示搜索项目列表的搜索片段。如果用户输入某些内容,我会将该字符串作为新的查询参数传递给 url,并使用 paging 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)
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

通过此解决方案,通过更改 url ( showPostList(newUrl),列表保持不变。也许在 viewModel 中使用缓存列表。

另一种解决方案是:使用showPostList(initUrl)in onViewCreatedof 片段,然后通过更改参数使用 blow 方法:

//fragment
fun changePostList(url: String) {
        viewModel.postListUrl = url
        postListAdapter.refresh()
    }
Run Code Online (Sandbox Code Playgroud)

这项工作有效,但如果旧列表和新列表有共同的项目,新列表将显示在最后一个共同的可见项目上。例如,如果旧列表的第 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)
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

但通过使用此列表刷新回到片段,有时Recyclerview状态会发生变化。

Raj*_*egi 6

class MyViewModel:ViewModel(){
  private val _currentQuery = MutableLiveData<String>()
  val currentQuery:LiveData<String> = _currentQuery


  val users = _currentQuery.switchMap { query->
      Pager(PagingConfig(pageSize = 20)) {
      PostPagingSource(postRepository, query)
  }.livedata.cachedIn(viewModelScope)

  }


  fun setCurrentQuery(query: String){
       _currentQuery.postValue(query)
  }
}
Run Code Online (Sandbox Code Playgroud)

通过使用

切换映射

每次查询更改时您都可以获得新结果,并且它将替换旧数据。