Android MVP+Retrofit(封裝)+RxJava實例

Github地址java

效果圖以下;react

mvp.gif

MVPandroid

mvp1.png

Retrofit
Retrofit是Square開發的一個Android和java的REST客戶端庫。git

這兩天工做不是很忙,寫了一個當前流行的Android MVP+Retrofit(封裝)+RxJava實例,mvp和retrofit我就不詳細講的,之後會詳細寫,下面直接上demo!github

1.分類
首先咱們要規劃好包名和類的分類,不要把類隨隨便便放,以下圖:api

example.jpg

除了上圖的模式,咱們還能夠把全部mvp類放在mvp包下,而後再按照上圖寫。ide

2.添加依賴和權限ui

compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'io.reactivex:rxandroid:1.2.1'
    compile 'io.reactivex:rxjava:1.1.6'
    compile 'com.google.code.gson:gson:2.8.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
<uses-permission android:name="android.permission.INTERNET"/>

3.定義Model--實體類 與URL接口
Model其實就是咱們經常寫的實體類,通常直接可在AS的GsonFormat插件上生成就能夠了.這裏我就不貼出來了this

URL接口以下:google

public interface ApiService {

    //baseUrl
    String API_SERVER_URL = "http://apistore.baidu.com/microservice/";

    //加載天氣
    @GET("weather")
    Observable<WeatherModel> loadDataByRetrofitRxjava(@Query("citypinyin") String cityId);

//    @FormUrlEncoded
//    @POST("user/login")
//    Observable<WeatherModel> getlogin(@Field("oper_name") String page, @Field("oper_pwds") String rows);
}

這就須要咱們對Retrofit的註解好好去看一看.

5.鏈接通訊(已封裝)
其實就是下面的代碼,這些我已經封裝了,請下載查看。

public static Retrofit retrofit() {
        if (mRetrofit == null) {
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            OkHttpClient okHttpClient = builder.build();
            mRetrofit = new Retrofit.Builder()
                    .baseUrl(ApiService.API_SERVER_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .client(okHttpClient)
                    .build();
        }
        return mRetrofit;
    }

6.View類

public interface WeatherView {

    void getWeatherSuccess(WeatherModel weatherModel);
}

下面是activity:

public class MainActivity extends AppCompatActivity  implements WeatherView,View.OnClickListener {
    private Button btn;
    private TextView tv_show;
    private EditText edt;
    private WeatherPresenter weatherpresenter=new WeatherPresenter(this);


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();

    }

    private void initView() {
        tv_show= (TextView) findViewById(R.id.tv_show);
        btn= (Button) findViewById(R.id.btn);
        edt= (EditText) findViewById(R.id.edt);
        btn.setOnClickListener(this);
    }

    @Override
    public void getWeatherSuccess(WeatherModel weatherModel) {

tv_show.setText("  "+weatherModel.getRetData().getWeather()+"  "+weatherModel.getRetData().getWD());

    }


    @Override
    public void onClick(View v) {
       switch (v.getId()){
           case R.id.btn:

               weatherpresenter.loadDataByRetrofitRxjava11111(edt.getText().toString());

               break;
       }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (weatherpresenter!=null){
            weatherpresenter.detachView();
            Log.e("RXJAVA","毀滅");
        }
    }
}

7.Presenter類

首先寫一個BasePresenter:

public class BasePresenter<V> {
    public V mvpView;

    protected ApiService apiStores;
    private CompositeSubscription mCompositeSubscription;

    public void attachView(V mvpView) {
        this.mvpView = mvpView;
        apiStores = ApiClient.retrofit().create(ApiService.class);
    }

    public void detachView() {
        this.mvpView = null;
        onUnsubscribe();
    }

    //RXjava取消註冊,以免內存泄露
    public void onUnsubscribe() {
        if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }
    }


    public <T> void addSubscription(Observable<T> observable, Subscriber<T> subscriber) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber));
    }
}

下面是WeatherPresenter:

public class WeatherPresenter extends BasePresenter<WeatherView>{

    public WeatherPresenter(WeatherView view) {
        attachView(view);
    }
    
    public void loadDataByRetrofitRxjava11111(String cityId) {
        addSubscription(apiStores.loadDataByRetrofitRxjava(cityId), new Subscriber<WeatherModel>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(WeatherModel weatherModel) {
          //  Log.e("請求成功","111");
                mvpView.getWeatherSuccess(weatherModel);
            }
        });
}
}
}

個人公衆號以下:

qzs1.jpg

相關文章
相關標籤/搜索