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

相关文章
相关标签/搜索