您需要将搜索键保存在实时数据中,以便分页列表在发生更改时可以更改。因此,在您的视图模型中,定义:
public MutableLiveData<String> filterTextAll = new MutableLiveData<>();
由于 pagedlist 也被定义为 LiveData,因此这可以借助 Transformation 来完成。 Transformations 类为您提供了可以更改 LiveData 对象中的值的函数。 swithMap 函数返回一个新的 LiveData 对象而不是一个值,在您的情况下,通过在后台创建新数据源,将 searchkey 切换为获取与 searchkey 对应的 pagedList 对象。
pagedListLiveData = Transformations.switchMap(filterTextAll, input -> {
MyDataSourceFactory myDataSourceFactory = new MyDataSourceFactory(executor,input);
myDataSource = myDataSourceFactory.getMyDataSourceMutableLiveData();
networkState = Transformations.switchMap(myDataSource,
dataSource -> dataSource.getNetworkState());
return (new LivePagedListBuilder(myDataSourceFactory, pagedListConfig))
.setFetchExecutor(executor)
.build();
});
您可以更改 DataSourceFactory 和 DataSource 构造函数以添加 searchKey 参数:
public class MyDataSourceFactory extends DataSource.Factory {
MutableLiveData<MyDataSource> myDataSourceMutableLiveData;
private MyDataSource myDataSource;
private Executor executor;
private String searchKey;
public MyDataSourceFactory(Executor executor , String searchKey) {
this.executor= executor;
this.searchKey= searchKey;
this.myDataSourceMutableLiveData= new MutableLiveData<>();
}
@Override
public DataSource create() {
//*notice: It's important that everytime a DataSource factory create() is invoked a new DataSource instance is created
myDataSource= new MyDataSource(executor, searchKey);
myDataSourceMutableLiveData.postValue(myDataSource);
return myDataSource;
}
public MutableLiveData<MyDataSource> getMyDataSourceMutableLiveData() {
return myDataSourceMutableLiveData;
}
public MyDataSource getMyDataSource() {
return myDataSource;
}
}
对 DataSource 构造函数执行与上面相同的操作,以传递 searchKey 以在 api 调用中使用。
还剩下一件事,在您的 Activity/Fragment (lifeCycleOwner) 中,每当 searchkey 更改触发时,请设置 filterTextAll mutableLiveData 的值,例如触发 searchview onQueryTextChange 或您喜欢的任何事件。
private void performSearch(String searchKey) {
// TODO: Perform the search and update the UI to display the results.
myViewModel.filterTextAll.setValue(searchKey);
myViewModel.pagedListLiveData.observe(owner, new Observer<PagedList<MyItem>>() {
@Override
public void onChanged(PagedList<MyItem> myItems) {
myAdapter.submitList(myItems);
}
});
myViewModel.networkState.observe(owner, new Observer<NetworkState>() {
@Override
public void onChanged(NetworkState networkState) {
myAdapter.setNetworkState(networkState);
}
});
myRecyclerView.setAdapter(myAdapter);
}