分页库过滤/搜索 [英] Paging Library Filter/Search
问题描述
我正在使用 Android 分页库,如下所述:https://developer.android.com/topic/libraries/architecture/paging.html
但我也有一个 EditText 用于按名称搜索用户.
如何过滤 Paging 库中的结果以仅显示匹配的用户?
您可以使用 MediatorLiveData 解决此问题.
特别是Transformations.switchMap
.
//原代码,后期改进公共无效重新加载任务(){if(liveResults != null) {liveResults.removeObserver(this);}liveResults = getFilteredResults();liveResults.observeForever(this);}
但如果你仔细想想,你应该能够在不使用 observeForever
的情况下解决这个问题,尤其是当我们考虑到 switchMap
也在做类似的事情时.>
所以我们需要的是一个LiveData
,它被切换映射到我们需要的LiveData
.
private final MutableLiveDatafilterText = savedStateHandle.getLiveData(filterText")私有最终 LiveData>数据;公共 MyViewModel() {数据 = Transformations.switchMap(过滤文本,(输入)->{if(input == null || input.equals("")) {返回 repository.getData();} 别的 {返回 repository.getFilteredData(input);}}});}公共 LiveData>获取数据(){返回数据;}
通过这种方式,从一个到另一个的实际更改由 MediatorLiveData 处理.
I am using the Android Paging Library like described here: https://developer.android.com/topic/libraries/architecture/paging.html
But i also have an EditText for searching Users by Name.
How can i filter the results from the Paging library to display only matching Users?
You can solve this with a MediatorLiveData.
Specifically Transformations.switchMap
.
// original code, improved later
public void reloadTasks() {
if(liveResults != null) {
liveResults.removeObserver(this);
}
liveResults = getFilteredResults();
liveResults.observeForever(this);
}
But if you think about it, you should be able to solve this without use of observeForever
, especially if we consider that switchMap
is also doing something similar.
So what we need is a LiveData<SelectedOption>
that is switch-mapped to the LiveData<PagedList<T>>
that we need.
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;
}
This way the actual changes from one to another are handled by a MediatorLiveData.
这篇关于分页库过滤/搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!