I'm using the Paging library.
Currently, I want to sort (using SortList) the items by the description in PagedListAdapter but I have not figured out how to do it.
How to sort elements when using a PagedListAdapter? Thank you.
I faced this problem too, and was surprised that PagedList
doesn't seem to have a straightforward way to sort items. Here's how I achieved the effect I needed using DataSource's mapByPage()
:
/** sorts MyItems by timestamp in descending order */
private fun DataSource.Factory<Long, MyItem>.sortByDescTime(): DataSource.Factory<Long, MyItem> {
return mapByPage {
myItemsList.sortedWith(compareByDescending { item -> item.timeStamp })
}
}
i.e, the input of mapByPage()
should be your sorting function (depends on your setup, mine uses the Kotlin extensions & lambda syntax to sort the items in the target list - using Collections.sortedWith()
)
And then, used my extension function on the data source to sort the fetched items:
fun fetchItems(userId: Long): LiveData<PagedList<MyItem>> {
val itemDataSource = itemAPIService.getItems(userId).sortByDescTime()
val itemPagedList = LivePagedListBuilder(itemDataSource, 10).build()
return itemPagedList
}
you need to use MediatorLiveData here. though below code is in java, it should serve the basic purpose. In Your ViewModel add both
public LiveData<PagedList<Customer>> customerList;
public MediatorLiveData<PagedList<Customer>> customerListMediator;
then first fetch liveData, that is, customerList in my case
customerList = new LivePagedListBuilder<>(mAppRepository.getCustomers(new SimpleSQLiteQuery(dynamicQuery)),1).build();
after that use the mediatorLiveData:-
customerListMediator.addSource(customerList, new Observer<PagedList<Customer>>() {
@Override
public void onChanged(@Nullable PagedList<Customer> customers) {
customerListMediator.setValue(customers);
}
});
And in your recyclerview, don't use LiveData list, instead use mediatorLiveData, in my case customerListMediator. like below:-
mViewModel.customerListMediator.observe(this, customers -> {
mViewModel.customerListAdapter.submitList(customers);
Toast.makeText(this, "list updated.", Toast.LENGTH_SHORT).show();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With