Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array items when using PagedListAdapter?

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.

like image 818
MrTy Avatar asked Jul 13 '18 08:07

MrTy


2 Answers

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
}
like image 168
kip2 Avatar answered Oct 31 '22 18:10

kip2


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();
    });
like image 39
Bharat Kumar Avatar answered Oct 31 '22 20:10

Bharat Kumar