How to implement SwipeRefreshLayout with the new Paging Library
Add a method in ViewModel class
public void refresh() {
itemDataSourceFactory.getItemLiveDataSource().getValue().invalidate();
}
and from the Activity/Fragment you can use
swipeRefreshLayout.setOnRefreshListener(() -> yourviewModel.refresh());
Hide the refresh layout when the reyclerView gets loaded
yourViewModel.itemPagedList.observe(this, allProposalModel -> {
mAdapter.submitList(model);
swipeRefreshLayout.setRefreshing(false); //here..
});
After calling the mDataSource.invalidate() method, mDataSource will be invalidated and the new DataSource instance will be created via DataSource.Factory.create() method, so its important to provide new DataSource() instance every time inside DataSource.Factory.create() method, do not provide same DataSource instance every time.
mDataSource.invalidate() is not working, because after invalidation, CouponListDataSourceFactory provides the same, already invalidated DataSource instance.
After modification CouponListDataSourceFactory will be looked like in below smple, and call to mCouponListDataSourceFactory.dataSource.invalidate() method will make a refresh, alternatively instead of keeping dataSource instance inside the factory, we can call invalidate method on LiveData< PagedList < CouponModel > >.getValue().getDataSource().invalidate()
public class CouponListDataSourceFactory extends DataSource.Factory {
private CouponListDataSource dataSource;
private CouponRepository repository;
private String token;
private String vendorId;
public CouponListDataSourceFactory(CouponRepository repository, String token, String vendorId) {
this.repository = repository;
this.token = token;
this.vendorId = vendorId;
}
@Override
public DataSource create() {
dataSource = new CouponListDataSource(repository, token, vendorId);
return dataSource;
}
}