Could not filter a PagedList?
Asked Answered
L

1

15

I've implemented a recyclerview with paging with the Android's Paging Library (https://developer.android.com/topic/libraries/architecture/paging.html). It works fine on fetching data and retrieve subsequent pages. However, how to filter the PagedList ? Say I have a Search widget, and I want to search the list currently on screen. PagedList.filter() returns a List and PagedListAdapter.setList() won't accept a List.

Lefevre answered 7/12, 2017 at 7:12 Comment(4)
A PagedList is a List.Patty
More info: #49193040Henebry
Hi do you have a code sample to achieve this?Galatia
I answered to similar question in https://mcmap.net/q/826700/-how-to-maintain-same-datasource-for-list-filter-and-search-in-android-paging-libraryRepay
I
0

I think you might be able to solve this with a MediatorLiveData.

Specifically Transformations.switchMap and some additional magic.

Currently I was using

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 that is switch-mapped to the LiveData> that we need.

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

This way the actual changes from one to another are handled by a MediatorLiveData. If we want to cache the LiveDatas, then we can do in the anonymous instance that we pass to the method.

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) {
                // ...
            }
        }
Implicit answered 27/9, 2019 at 8:19 Comment(1)
Please credit original authors: https://mcmap.net/q/397218/-paging-library-filter-searchDiplegia

© 2022 - 2024 — McMap. All rights reserved.