1. 程式人生 > >MVP+RxAndroid+Retrogit封裝的獲取網路(2)

MVP+RxAndroid+Retrogit封裝的獲取網路(2)

上篇部落格簡單的介紹但是沒有結合實際,下面我們這篇只說下如何進行真實的請求網路應用
基礎介紹

效果:UI佈局詳解
在這裡插入圖片描述

1.匯入依賴

   //fresco
    implementation 'com.facebook.fresco:fresco:1.11.0'
    //recyclerview列表展示
    implementation 'com.android.support:recyclerview-v7:28.0.0'
    implementation 'com.jcodecraeer:xrecyclerview:1.2.0'
    //Rxjava和RxAndroid
    implementation 'io.reactivex.rxjava2:rxjava:2.2.4'
    implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'
    //butterknife
    implementation 'com.jakewharton:butterknife:8.8.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
    //retrofit
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
    //卡片佈局
    implementation 'com.android.support:cardview-v7:28.0.0'

2.MainActivity佈局

	<com.jcodecraeer.xrecyclerview.XRecyclerView
        android:id="@+id/main_xrv_showlist"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

3.MainActivity程式碼

	public class MainActivity extends BaseMVP<GoodsView,GoodsPresenter> {

    //找控制元件
    @BindView(R.id.main_xrv_showlist)
    XRecyclerView mXRecyclerView;

    private Unbinder mBind;
    private MyAdapter mAdapter;

    @Override
    public GoodsPresenter initPresenter() {
        //例項化P
        return new GoodsPresenter();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //註冊Butterknife
        mBind = ButterKnife.bind(this);

    }

    @Override
    protected int initLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initData() {
        presenter.getData(new GoodsView<NetWork>() {
            @Override
            public void success(NetWork data) {
                List<NetWork.DataBean> list = data.getData();
                //設定資料
                mAdapter.setData(list);
                //設定介面卡
                mXRecyclerView.setAdapter(mAdapter);
                //佈局管理器
                mXRecyclerView.setLayoutManager(new GridLayoutManager(MainActivity.this,2));
            }
        });
    }

    @Override
    protected void initView() {
        //建立介面卡
        mAdapter = new MyAdapter(this);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消註冊Butterknife
        mBind.unbind();

    }
}

4.看到了上面Activity的繼承,那麼下面就開始我們寫我們的MVP+Retrofit+RxJava

Presenter程式碼

/**
 * date:2018/12/18
 * author:輝(家輝輝輝)
 * function:P層的基類
 */
public class BasePresenter<T>{

    public T view;

    //建立
    public void attach(T view){
        this.view = view;
    }

    //銷燬
    public void detach(){
        this.view = null ;
    }
}

MVP的基類,注意一點,並不是所有的介面都要用MVP所以我們就不繼承基類了,不需要MVP的介面再寫基類

/**
 * date:2018/12/18
 * author:輝(家輝輝輝)
 * function:MVP的基類
 *  這裡用V,T主要是代表了通用性,一個介面適合被不同型別的Activity繼承
 */
public abstract class BaseMVP<V,T extends BasePresenter<V>> extends Activity {

    //宣告變數
    public T presenter;

    //初始化P
    public abstract T initPresenter();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(initLayout());
        
        //進行賦值讓我們在繼承這個Activity的時候就自動生成帶返回值的方法,而且可以呼叫這個類的變數
        presenter = initPresenter();

        //初始化佈局
        initView();

        //初始化資料
        initData();
    }

    protected abstract int initLayout();

    protected abstract void initData();

    protected abstract void initView();

    @Override//建立
    protected void onResume() {
        super.onResume();
        presenter.attach((V) this);
    }

    @Override//置為空為了解決記憶體洩漏
    protected void onDestroy() {
        super.onDestroy();
        presenter.detach();
    }
}

下面就進行一個網路的傳值呼叫

請求網路的介面

public interface ApiServer {

    @GET("ad/getAd")//這個地方是請求體
    Observable<NetWork> getNetMessage();

}

請求網路的工具類

public class RetrofitUtils {
    
    //宣告類名
    private static volatile RetrofitUtils sRetrofitUtils;
    private final OkHttpClient mClient;


    //單例建立物件
    private RetrofitUtils() {
        //建立OkHttpClient,可以再次新增攔截器
        mClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .build();
    }
    
    //通過單例建立類
    public static RetrofitUtils getInstance(){
        if(sRetrofitUtils == null){
            synchronized (RetrofitUtils.class){
                if(sRetrofitUtils == null){
                    sRetrofitUtils = new RetrofitUtils();
                }
            }
        }
        return sRetrofitUtils;
    }

    //暴露方法
    public Observable<NetWork> doGet(String url){

        //建立介面
        ApiServer apiServer = new Retrofit.Builder()
                .client(mClient)
                .baseUrl(url)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build().create(ApiServer.class);
        
        //返回方法,並設定非同步
        return apiServer.getNetMessage()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

}

M層呼叫工具類

public class GoodsModel {

    //方法、傳入介面
    public void getData(final GoodsView<NetWork> goodsView){
        //通過單例獲取例項
        RetrofitUtils instance = RetrofitUtils.getInstance();

        //呼叫方法
        Observable<NetWork> netWorkObservable = instance.doGet(CaUrl.goodsUrl);

        //通過訂閱傳給觀察者
        netWorkObservable.subscribe(new Observer<NetWork>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(NetWork netWork) {
                if(netWork != null){
                    //存入介面
                    goodsView.success(netWork);
                }

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

}

P層調M層,這裡的P就要繼承P層的基類了

public class GoodsPresenter extends BasePresenter<GoodsView> {

    private final GoodsModel model;

    //無參構造
    public GoodsPresenter() {
        //宣告並例項化M層
        model = new GoodsModel();
    }

    //封裝方法傳入介面
    public void getData(final GoodsView<NetWork> goodsView){
        model.getData(new GoodsView<NetWork>() {
            @Override
            public void success(NetWork data) {
                //存在
                goodsView.success(data);
            }
        });
    }
}

然後我們再去MainActivity,就會很清楚的看到這層關係