0

I am working on a sample Android app and i am trying to implement a presenter class since i follow MVP pattern. My presenter implementation is below

public class WeatherForecastPresenter extends AsyncTask<Void, Void, WeatherForecast> {

    private double latitude;
    private double longitude;
    private String address;

    // class that makes sync OkHttp call
    private WeatherForecastService weatherForecastService;
    // interface that has callback methods
    private WeatherForecastView weatherForecastView;

    public WeatherForecastPresenter(WeatherForecastView weatherForecastView, double latitude, double longitude, String address) {
        this.latitude = latitude;
        this.longitude = longitude;
        this.address = address;

        this.weatherForecastView = weatherForecastView;
        weatherForecastService = new WeatherForecastService();
    }

    @Override
    protected void onPreExecute() {
        weatherForecastView.toggleRefresh();
    }

    @Override
    protected WeatherForecast doInBackground(Void... voids) {
        // gets weather forecast data of given location
        return weatherForecastService.getCurrentWeather(latitude, longitude);
    }

    @Override
    protected void onPostExecute(WeatherForecast weatherForecast) {
        weatherForecastView.toggleRefresh();

        if (weatherForecast != null) {
            weatherForecastView.updateUi(weatherForecast, address);
        } else {
            weatherForecastView.displayErrorDialog();
        }
    }
}

I am looking for the best practice for implementing a presenter class and i believe moving AsyncTask to a seperate class and implementing it in a more generic way would be a better approach but i could not find a proper solution. I would be appreciated if you can help me about it.

Tartar
  • 5,149
  • 16
  • 63
  • 104

2 Answers2

0

Try using retrofit2 for requests & RxJava for data flow handling.

Presenter shouldn't extend AsyncTask.

Valentin Baryshev
  • 2,195
  • 3
  • 15
  • 24
0

The best way would be to use Loaders. Take a look here.

You need the AsyncTaskLoader. There are a lot of improvements in Loaders vs. the old AsyncTask.

Official documentation here. Also, using Loaders you don't have to worry about the activity lifecycle.

jorjSB
  • 610
  • 4
  • 12