簡體   English   中英

Android MVP:最佳做法

[英]Android MVP: Best Practice

我正在研究一個示例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移到單獨的類並以更通用的方式實現將是更好的方法,但我找不到合適的解決方案。 如果您能幫助我,我將不勝感激。

嘗試使用retrofit2的請求和RxJava實現數據流的處理。

演示者不應擴展AsyncTask。

最好的方法是使用裝載機。 在這里看看。

您需要AsyncTaskLoader。 與舊的AsyncTask相比,Loader有很多改進。

官方文檔在這里 此外,使用裝載程序,您不必擔心活動生命周期。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM