Android-CleanArchitecture icon indicating copy to clipboard operation
Android-CleanArchitecture copied to clipboard

Pull to Refresh

Open migelfn opened this issue 8 years ago • 0 comments

How do you guys implement pull to refresh?

We need to:

  1. Fetch data from the network.
  2. Replace previously cached data.
  3. Update recycler view data.

What we did:

  1. View calls mPresenter.load(refresh = true).
  2. Presenter calls mUseCase.execute(refresh = true).
  3. UseCase calls mRepository.getData(refresh = true).
  4. Repository checks if refresh = true then fetch data from network else fetch data from cache.

Here's a sample code

PlaygroundView.java

public interface PlaygroundView extends MvpView {

    void showLoading(boolean refresh);

    void showContent(boolean refresh, List<Playground> playgrounds);

    void showError(boolean refresh, @NonNull String message);
}

PlaygroundPresenter.java

public class PlaygroundPresenter extends RxPresenter<PlaygroundView> {

    private final GetPlaygrounds mGetPlaygrounds;

    @Inject
    public PlaygroundPresenter(@NonNull GetPlaygrounds getPlaygrounds) {
        mGetPlaygrounds = getPlaygrounds;
    }

    public void loadPlaygrounds(boolean refresh) {
        getView().showLoading(refresh);

        mGetPlaygrounds.execute(refresh)
                .compose(bindToLifecycle())
                .subscribe(playgrounds -> {
                    getView().showContent(refresh, playgrounds);
                }, error -> {
                    Logger.e(error, "Get playgrounds failed.");
                    getView().showError(refresh, error.getMessage());
                });
    }
}

GetPlaygrounds.java

public class GetPlaygrounds extends BaseUseCase {

    private final PlaygroundRepository mPlaygroundRepository;

    @Inject
    public GetPlaygrounds(@NonNull PlaygroundRepository playgroundRepository) {
        mPlaygroundRepository = playgroundRepository;
    }

    public Observable<List<Playground>> execute(boolean refresh) {
        return mPlaygroundRepository.getPlaygrounds(refresh)
                .compose(applySchedulers());
    }
}

PlaygroundRepository.java

@Singleton
public class PlaygroundRepository extends Repository {

    @Inject
    public PlaygroundRepository() {
    }

    public Observable<List<Playground>> getPlaygrounds(boolean refresh) {
        if (refresh) {
            // Fetch data from network
        } else {
            // Fetch data from cache 
        }
    }
}

migelfn avatar Apr 12 '17 00:04 migelfn