Android MVP:最佳做法

问题描述 投票:0回答:2

我正在研究一个示例Android应用程序,并且由于遵循MVP模式,因此我试图实现Presenter类。 我的主持人实施如下

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();
        }
    }
}

我正在寻找实现presenter类的最佳实践,我相信将AsyncTask移到单独的类并以更通用的方式实现将是更好的方法,但我找不到合适的解决方案。 如果您能帮助我,我将不胜感激。

java android android-asynctask mvp android-mvp
2个回答
0
投票

尝试使用retrofit2的请求和RxJava实现数据流的处理。

演示者不应扩展AsyncTask。


0
投票

最好的方法是使用装载机。 在这里看看。

您需要AsyncTaskLoader。 与旧的AsyncTask相比,Loader有很多改进。

官方文档在这里 。 此外,使用装载程序,您不必担心活动生命周期。

© www.soinside.com 2019 - 2024. All rights reserved.