如何在Android分页库中为列表,过滤器和搜索维护相同的数据源

时间:2019-09-08 10:17:41

标签: android retrofit2 android-search android-paging android-paging-library

我正在进行显示项目列表的活动,并且还具有过滤器和搜索选项。我正在使用android分页库显示项目。第一次滚动项目列表时,当我滚动到要加载的下一组项目的底部时,它的工作正常。但我也想过滤项目并搜索项目。在“筛选或搜索项目”上,我使现有资源无效。如果没有使“数据源”无效,则过滤器和Search api无法触发。我想使用数据源基于我的过滤器和“搜索”键加载新项目列表。

executor = Executors.newFixedThreadPool(5);
    celebrityDataFactory = new CelebrityDataFactory(apicallInterface,         mFansismParam);
    networkState =  Transformations.switchMap(celebrityDataFactory.getCelebrityData(),
            dataSource -> dataSource.getNetworkState());

    PagedList.Config pagedListConfig =
            (new PagedList.Config.Builder())
                    .setEnablePlaceholders(false)
                    .setPrefetchDistance(8)
                    .setInitialLoadSizeHint(10)
                    .setPageSize(20).build();
    if (!mFansismParam.getCategoryId().isEmpty()) {
        celebrityDetails = new LivePagedListBuilder(celebrityDataFactory, pagedListConfig)
                .setFetchExecutor(executor)
                .build();
    } else(!mFansismParam.getProfessionId().isEmpty()) {
        celebrityDetails = new LivePagedListBuilder(celebrityDataFactory, pagedListConfig)
                .setFetchExecutor(executor)
                .build();
    }

数据工厂以创建数据源

@Override
public DataSource create() {
    celebrityDataSource = new CelebrityDataSource(apicallInterface,   params);
    celebrityData.postValue(celebrityDataSource);
    return celebrityDataSource;
}

改造API调用:

 Call<CelebrityList> getCelebrityList(@Query("categoryId") String categoryId,
                                     @Query("professionId") String professionId,
                                     @Query("page") String pageNumber,
                                     @Query("name") String searchKey);

数据源Api回调:

apicallInterface.getCelebrityList(requestParams.getCategoryId(), "", "1", "").enqueue(new Callback<CelebrityList>() {
        @Override
        public void onResponse(Call<CelebrityList> call, Response<CelebrityList> response) {
            if (response.isSuccessful()) {
                initialLoading.postValue(NetworkState.LOADED);
                networkState.postValue(NetworkState.LOADED);
                if (!response.body().getData().isEmpty()) {
                    callback.onResult(response.body().getData(), null, "2");
                } else {
                    networkState.postValue(new NetworkState(NetworkState.Status.SUCCESS, "No more results"));
                }
            } else {
                initialLoading.postValue(new NetworkState(NetworkState.Status.FAILED, response.message()));
                networkState.postValue(new NetworkState(NetworkState.Status.FAILED, response.message()));
            }
        }

1 个答案:

答案 0 :(得分:2)

您需要在实时数据中按住搜索键,以便可以随时更改pagedlist。因此,在您的视图模型中,定义:

public MutableLiveData<String> filterTextAll = new MutableLiveData<>();

由于页面列表也被定义为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构造函数进行与上述相同的操作,以传递要在api调用中使用的searchKey。 还有一件事,只要触发搜索键更改(例如触发searchview onQueryTextChange或您喜欢的任何事件),就在您的Activity / Fragment(lifeCycleOwner)中设置filterTextAll mutableLiveData的值。

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);
          }