38

我正在使用此处描述的 Android 分页库: https ://developer.android.com/topic/libraries/architecture/paging.html

但我也有一个 EditText 用于按名称搜索用户。

如何过滤 Paging 库中的结果以仅显示匹配的用户?

4

3 回答 3

42

您可以使用 MediatorLiveData 解决此问题。

具体来说Transformations.switchMap

// original code, improved later
public void reloadTasks() {
    if(liveResults != null) {
        liveResults.removeObserver(this);
    }
    liveResults = getFilteredResults();
    liveResults.observeForever(this);
}

但是如果你考虑一下,你应该能够在不使用 的情况下解决这个问题observeForever,特别是如果我们认为它switchMap也在做类似的事情。

所以我们需要的是一个LiveData<SelectedOption>开关映射到LiveData<PagedList<T>>我们需要的。

private final MutableLiveData<String> filterText = savedStateHandle.getLiveData("filterText")

private final LiveData<List<T>> data;

public MyViewModel() {
    data = Transformations.switchMap(
            filterText,
            (input) -> { 
                if(input == null || input.equals("")) { 
                    return repository.getData(); 
                } else { 
                    return repository.getFilteredData(input); }
                }
            });
  }

  public LiveData<List<T>> getData() {
      return data;
  }

这样,从一个到另一个的实际更改由 MediatorLiveData 处理。

于 2018-03-09T12:01:29.903 回答
25

我使用了类似于 EpicPandaForce 回答的方法。虽然它正在工作,但这种订阅/取消订阅似乎很乏味。我已经开始使用其他数据库而不是 Room,所以无论如何我都需要创建自己的 DataSource.Factory。显然,可以使当前的 DataSource 无效,并且 DataSource.Factory 创建一个新的 DataSource,这就是我使用搜索参数的地方。

我的 DataSource.Factory:

class SweetSearchDataSourceFactory(private val box: Box<SweetDb>) :
DataSource.Factory<Int, SweetUi>() {

var query = ""

override fun create(): DataSource<Int, SweetUi> {
    val lazyList = box.query().contains(SweetDb_.name, query).build().findLazyCached()
    return SweetSearchDataSource(lazyList).map { SweetUi(it) }
}

fun search(text: String) {
    query = text
}
}

我在这里使用 ObjectBox,但你可以在创建时返回你的房间 DAO 查询(我猜它已经是一个 DataSourceFactory,调用它自己的创建)。

我没有测试它,但这可能有效:

class SweetSearchDataSourceFactory(private val dao: SweetsDao) :
DataSource.Factory<Int, SweetUi>() {

var query = ""

override fun create(): DataSource<Int, SweetUi> {
    return dao.searchSweets(query).map { SweetUi(it) }.create()
}

fun search(text: String) {
    query = text
}
}

当然,可以通过来自 dao 的查询来传递一个工厂。

视图模型:

class SweetsSearchListViewModel
@Inject constructor(
private val dataSourceFactory: SweetSearchDataSourceFactory
) : BaseViewModel() {

companion object {
    private const val INITIAL_LOAD_KEY = 0
    private const val PAGE_SIZE = 10
    private const val PREFETCH_DISTANCE = 20
}

lateinit var sweets: LiveData<PagedList<SweetUi>>

init {
    val config = PagedList.Config.Builder()
        .setPageSize(PAGE_SIZE)
        .setPrefetchDistance(PREFETCH_DISTANCE)
        .setEnablePlaceholders(true)
        .build()

    sweets = LivePagedListBuilder(dataSourceFactory, config).build()
}

fun searchSweets(text: String) {
    dataSourceFactory.search(text)
    sweets.value?.dataSource?.invalidate()
}
}

但是接收到搜索查询,只需在 ViewModel 上调用 searchSweets。它在工厂中设置搜索查询,然后使数据源无效。反过来,在工厂中调用 create 并使用新查询创建 DataSource 的新实例,并在后台传递给现有的 LiveData。

于 2018-06-20T16:07:59.840 回答
0

您可以使用上面的其他答案,但这是另一种方法:您可以让工厂根据您的需求生成不同的数据源。它是这样完成的:在您的DataSource.Factory类中,为初始化 YourDataSource 所需的参数提供设置器

private String searchText;
...
public void setSearchText(String newSearchText){
    this.searchText = newSearchText;
}
@NonNull
@Override
public DataSource<Integer, SearchItem> create() {
    YourDataSource dataSource = new YourDataSource(searchText); //create DataSource with parameter you provided
    return dataSource;
}

当用户输入新的搜索文本时,让您的 ViewModel 类设置新的搜索文本,然后在 DataSource 上调用无效。在您的活动/片段中:

yourViewModel.setNewSearchText(searchText); //set new text when user searchs for a text

在您的 ViewModel 中,定义该方法以更新 Factory 类的 searchText:

public void setNewSearchText(String newText){
   //you have to call this statement to update the searchText in yourDataSourceFactory first
   yourDataSourceFactory.setSearchText(newText);
   searchPagedList.getValue().getDataSource().invalidate(); //notify yourDataSourceFactory to create new DataSource for searchPagedList
}

当 DataSource 失效时,DataSource.Factory 会调用它的 create() 方法,用你设置的 newText 值创建新的 DataSource。结果将是相同的

于 2021-04-16T05:45:58.147 回答