【问题标题】:Could not filter a PagedList?无法过滤 PagedList?
【发布时间】:2018-05-21 05:35:45
【问题描述】:

我已经使用 Android 的分页库 (https://developer.android.com/topic/libraries/architecture/paging.html) 实现了一个带有分页功能的 recyclerview。它适用于获取数据和检索后续页面。但是,如何过滤 PagedList ?假设我有一个搜索小部件,我想搜索当前屏幕上的列表。 PagedList.filter() 返回 List 并且 PagedListAdapter.setList() 不会接受 List

【问题讨论】:

标签: android android-recyclerview android-pageradapter pagedlist


【解决方案1】:

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

特别是 Transformations.switchMap 和一些额外的魔法。

目前我正在使用

public void reloadTasks() {
    if(liveResults != null) {
        liveResults.removeObserver(this);
    }
    liveResults = getFilteredResults();
    liveResults.observeForever(this);
}

但是如果你仔细想想,你应该可以不使用observeForever来解决这个问题,特别是如果我们认为switchMap也在做类似的事情。

所以我们需要一个 LiveData,它被开关映射到我们需要的 LiveData>。

private MutableLiveData<String> filterText = new MutableLiveData<>();

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 处理。如果我们想要缓存 LiveData,那么我们可以在传递给方法的匿名实例中进行。

data = Transformations.switchMap(
        filterText, new Function<String, LiveData<List<T>>>() {
            private Map<String, LiveData<List<T>>> cachedLiveData = new HashMap<>();

            @Override
            public LiveData<List<T>> apply(String input) {
                // ...
            }
        }

【讨论】:

猜你喜欢
  • 2015-12-08
  • 2015-11-21
  • 1970-01-01
  • 1970-01-01
  • 2013-09-14
  • 2012-05-26
  • 2018-12-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多