1. 程式人生 > >Android中的RxJava,Retrofit,MVP的使用

Android中的RxJava,Retrofit,MVP的使用

RxJava,Retrofit,MVP都是近幾年討論的比較熱門的話題,我們也來湊個熱鬧!

本博不展開討論,分別討論的文章有很多,後續有時間給出RxJava,Retrofit的原始碼分析

先來說一下MVP(Model View Presenter)熟悉MVC結構的應該很容易理解MVP,這裡先給出MVP的圖解

MVP圖解

  • model具體業務邏輯處理的實現
  • view負責顯示資料、提供友好介面跟使用者互動
  • presenter負責完成View於Model間的互動

下面給出一個使用這三者的demo,由於使用Retrofit和RxJava,資料獲取的過程變得很簡潔,此demo沒有按照嚴格的MVP結構,遵從了資料和view分開處理的原則,降低了程式碼的耦合度,少定義幾個介面

View程式碼層

package com.zimo.guo.activity;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import com.zimo.guo.R;
import com.zimo.guo.model.BannerVO;
import com.zimo.guo.presenter.BannerPresenter;

import java.util.List;

import butterknife.Bind;
import
butterknife.ButterKnife; public class MainActivity extends AppCompatActivity implements LoadingBannerView{ @Bind(R.id.show_banner_string) TextView showBanner; BannerPresenter presenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this
); presenter = new BannerPresenter(MainActivity.this); presenter.loadData(); } @Override public void showData(List<BannerVO> bannerVOs) { showBanner.setText(bannerVOs.get(0).getPicUrl()); } @Override public void showNetworkErrorView() { } @Override public void hideNetworkErrorView() { } @Override public void showLoading() { } @Override public void hideLoading() { } @Override public void showEmptyView() { } @Override public void hideEmptyView() { } @Override public void showError(String message) { } }

寫的比較簡單,根據需求私人私人定製

view層的介面

package com.zimo.guo.activity;

import com.zimo.guo.model.BannerVO;

import java.util.List;

/**
 * @Description:
 * @author: zimo
 * @date: 2016-04-25
 */
public interface LoadingBannerView extends LoadingDataView{

    void showData(List<BannerVO> bannerVOs);
}
package com.zimo.guo.activity;

import java.util.List;

/**
 * @Description: 載入資料
 * @author: zimo
 * @date: 2016-04-06
 */
public interface LoadingDataView {

    void showNetworkErrorView();

    void hideNetworkErrorView();

    void showLoading();

    void hideLoading();

    void showEmptyView();

    void hideEmptyView();

    void showError(String message);
}

present層程式碼

package com.zimo.guo.presenter;

import com.zimo.guo.activity.LoadingBannerView;
import com.zimo.guo.exception.NetworkConnectionException;
import com.zimo.guo.model.BannerVO;
import com.zimo.guo.network.service.HttpService;
import com.zimo.guo.rx.operator.OperatorRequestMap;

import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * @Description:
 * @author: zimo
 * @date: 2016-04-25
 */
public class BannerPresenter implements CommonPresenter {

    LoadingBannerView view;

    public BannerPresenter(LoadingBannerView view) {
        this.view = view;
    }

    @Override
    public void loadData() {
        HttpService.getInstance().getCommonApi().getBannerList("", "", "", "")
                .lift(new OperatorRequestMap<List<BannerVO>>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<List<BannerVO>>() {
                    @Override
                    public void call(List<BannerVO> bannerVOs) {
                        if (bannerVOs != null && bannerVOs.size() > 0) {
                            view.showData(bannerVOs);
                        }else {
                            view.showEmptyView();
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        if (throwable instanceof NetworkConnectionException) {
                            view.showNetworkErrorView();
                        }
                    }
                });
    }
}

present層的介面

package com.zimo.guo.presenter;

/**
 * @Description:
 * @author: zimo
 * @date: 2016-04-25
 */
public interface CommonPresenter {

    void loadData();
}

model層主要是實體,省略一百行程式碼…

RxJava使用

package com.zimo.guo.network.service;

import com.zimo.guo.BuildConfig;
import com.zimo.guo.constants.HttpContants;
import com.zimo.guo.network.api.CommonApi;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @Description: http
 * @author: zimo
 * @date: 2016-04-24
 */
public class HttpService {

    private CommonApi commonApi;

    private HttpService() {
        Retrofit.Builder builder = new Retrofit.Builder().addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(HttpContants.DEFAULT_HOST_URL);
        OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder().addNetworkInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                Request newReq = request.newBuilder()
                        .build();
                return chain.proceed(newReq);
            }
        });

        if (BuildConfig.DEBUG){
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            okHttpBuilder.addInterceptor(loggingInterceptor);
        }

        OkHttpClient client = okHttpBuilder.build();
        builder.client(client);
        commonApi = builder.build().create(CommonApi.class);
    }

    private static class HttpServiceHandler{
        public static final HttpService INSTANCE = new HttpService();
    }

    public static HttpService getInstance(){
        return HttpServiceHandler.INSTANCE;
    }

    public static CommonApi getCommonApi() {
        return HttpService.getInstance().commonApi;
    }
}

retrofit的使用

package com.zimo.guo.network.api;


import com.zimo.guo.model.BannerVO;
import com.zimo.guo.model.BaseBean;

import java.util.List;

import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
import rx.Observable;

/**
 * @Description:
 * @author: zimo
 * @date: 2016-04-24
 */
public interface CommonApi {

    @FormUrlEncoded
    @POST("")
    Observable<BaseBean<List<BannerVO>>> getBannerList(@Field("") String method, @Field("") String bannerUpdateVer, @Field("") String sessionKey,
                                                       @Field("") String bannerType);
}

欲知詳情,請聽下回解說