How to implement SwipeRefreshLayout with the new Paging Library

前端 未结 2 1786
情深已故
情深已故 2020-12-15 21:24

I got an activity that shows a list of items to the user and it uses the Paging Library. My problem is that I can\'t reload the list when user swipes down the screen so that

相关标签:
2条回答
  • 2020-12-15 21:55

    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..
    
    
        });
    
    0 讨论(0)
  • 2020-12-15 22:14

    After call 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;
    }
    }
    
    0 讨论(0)
提交回复
热议问题