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

Tha*_*nan 2 android android-search retrofit2 android-paging android-paging-library

我有显示项目列表的活动,还有过滤器和搜索选项。我正在使用 android 分页库显示项目。第一次加载项目列表时,当我滚动到底部加载下一组项目时,它的工作正常。但我也想过滤项目并搜索项目。在过滤或搜索项目上,我使现有源无效。如果不使数据源无效,则过滤器和搜索 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();
    }
Run Code Online (Sandbox Code Playgroud)

数据工厂创建数据源

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

改造 API 调用:

 Call<CelebrityList> getCelebrityList(@Query("categoryId") String categoryId,
                                     @Query("professionId") String professionId,
                                     @Query("page") String pageNumber,
                                     @Query("name") String searchKey);
Run Code Online (Sandbox Code Playgroud)

数据源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()));
            }
        }
Run Code Online (Sandbox Code Playgroud)

Rey*_*baf 5

您需要在实时数据中保存您的搜索键,以便在页面列表更改时可以更改它。所以在你的视图模型中,定义:

public MutableLiveData<String> filterTextAll = new MutableLiveData<>();
Run Code Online (Sandbox Code Playgroud)

由于分页列表也被定义为一个 LiveData,这可以在转换的帮助下完成。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();
      });
Run Code Online (Sandbox Code Playgroud)

您可以更改 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;
  }

}
Run Code Online (Sandbox Code Playgroud)

对 DataSource 构造函数执行与上面相同的操作,以传递 searchKey 以在 api 调用中使用。还有一件事,在您的 Activity/Fragment (lifeCycleOwner) 中设置 filterTextAll mutableLiveData 的值,无论何时触发 searchkey 更改,例如触发 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);
          }
Run Code Online (Sandbox Code Playgroud)