MVP+Rxjava+Retrofit构建项目

第一次写文章,不好之处还请谅解。2015最值得android程序猿去学习的就是rxjava了,关于rxjava就不再多描述了,本文是介绍怎么使用mvp+rxjava+retrofit来构建一个新的项目。 项目采用mvp的方式,参考了google的官方mvp项目。
Hot是关于微信头条分享的app
github地址
最近加入了dagger,传送门

项目介绍

1.BaseActivity的设计:

/**
 * Created by wukewei on 16/5/26.
 */
public abstract class BaseActivity extends AppCompatActivity {

    protected T mPresenter;
    protected Activity mContext;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayout());
        ButterKnife.bind(this);
        mContext = this;
        mPresenter = getPresenter();
        initEventAndData();
    }

    protected void setCommonBackToolBack(Toolbar toolbar, String title) {
        toolbar.setTitle(title);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        toolbar.setNavigationOnClickListener(v -> onBackPressed());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        if (mPresenter != null) mPresenter.detachView();
    }

    protected abstract T getPresenter();
    protected abstract int getLayout();
    protected abstract void initEventAndData();
}

最主要的设置了presenter的泛型,并且提供了初始化的函数 protected abstract T getPresenter();。

2.BasePresenter的设计

/**
 * Created by wukewei on 16/5/26.
 */
public abstract class BasePresenter implements IPresenter {

    protected Activity mActivity;
    protected T mView;
    protected CompositeSubscription mCompositeSubscription;
   // protected static final HotApi mHotApi = HotFactory.getHotApi();

    public BasePresenter(Activity activity, T view) {
        this.mActivity = activity;
        this.mView = view;
    }

    protected void handleError(Throwable throwable) {
        ToastUtil.showShort(mActivity, ErrorHanding.handleError(throwable));
    }

    protected void unSubscribe() {
        if (mCompositeSubscription != null) {
            mCompositeSubscription.unsubscribe();
        }
    }

    protected void addSubscrebe(Subscription subscription) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(subscription);
    }

    @Override
    public void detachView() {
        this.mView = null;
        unSubscribe();
    }
}

也采用了范型来绑定view,使用了CompositeSubscription来进行避免内存的泄漏。
3.Api的设计
在实际情况中每个公司的api的设计都是不一样的,我采用如下的设计形式。

/**
 * Created by wukewei on 16/5/26.
 */
public class ApiResponse {
    
    public static final int SUCCESS_CODE = 200;

    private int code;
    private String msg;
    private T newslist;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getNewsList() {
        return newslist;
    }

    public void setNewsList(T newsList) {
        this.newslist = newsList;
    }

    public boolean isSuccess() {
        if (this.code == SUCCESS_CODE) {
            return true;
        } else {
            return false;
        }
    }
}

你们可以根据自己公司的实际情况修改返回的成功码。
4.Rxjava的一些设计:
大家都知道rxjava就是能灵活的在线程之间进行切换,在使用的时候我使用了Transformer操作符。

/**
 * Created by wukewei on 16/5/26.
 */
public class SchedulersCompat {

    private final static Observable.Transformer ioTransformer = o -> o.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread());

    public static  Observable.Transformer applyIoSchedulers() {
        return (Observable.Transformer) ioTransformer;
    }
}

在数据处理的时候,

/**
 * Created by wukewei on 16/5/26.
 */
public class RxResultHelper {

    public static  Observable.Transformer, T> handleResult() {
        return apiResponseObservable -> apiResponseObservable.flatMap((Func1, Observable>) tApiResponse -> {
            if (tApiResponse.isSuccess()) {
                //表示成功
                return createData(tApiResponse.getNewsList());
            } else {
                return Observable.error(new ServerException(tApiResponse.getMsg()));
            }
        });
    }


    public static  Observable createData(T t) {
        return Observable.create(new Observable.OnSubscribe() {
            @Override
            public void call(Subscriber subscriber) {
                try {
                    subscriber.onNext(t);
                    subscriber.onCompleted();
                } catch (Exception e) {
                    subscriber.onError(e);
                }
            }
        });
    }
}

在这里你可以根据自己的实际情况来添加,大部分app都是有token一说,你可以在这里判断当token过期的时候可以跳到登录界面。
在项目中的时候就是

  Subscription subscription = mHotApi.getPopular(this.pn, Constants.PAGE_SIZE, type)
                    .compose(SchedulersCompat.applyIoSchedulers())
                    .compose(RxResultHelper.handleResult())
                    .subscribe(populars -> {
                        mView.showContent();
                        if (isRefresh()) {
                            if (populars.size() == 0) mView.showNotdata();
                            mView.addRefreshData(populars);
                        } else {
                            mView.addLoadMoreData(populars);
                        }
                    }, throwable -> {
                        mView.showError(ErrorHanding.handleError(throwable));
                        handleError(throwable);
                    });
            addSubscrebe(subscription);

是不是觉得使用起来非常的爽啊。
还有一个就是在实际情况中很多一部分请求要设置一些数据好比来自android的还是ios的,或者添加一些token在请求中,本项目没有使用token,但是有个apikey代码如下:

**
 * Created by wukewei on 16/5/26.
 */
public class OkHttpManager {

    private static OkHttpClient mOkHttpClient;

    public static OkHttpClient getInstance() {

        if (mOkHttpClient == null) {
            synchronized (OkHttpManager.class) {
                if (mOkHttpClient == null) {
                   HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
                   loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                    Interceptor apikey = chain -> chain.proceed(chain.request().newBuilder()
                            .addHeader("apikey", Constants.Api_Key).build());

                    File cacheFile = new File(App.getAppContext().getCacheDir(), "cache");
                    Cache cache = new Cache(cacheFile, 1024 * 1024 * 100); //100Mb
                    mOkHttpClient = new OkHttpClient.Builder()
                            .readTimeout(Constants.HTTP_CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
                            .connectTimeout(Constants.HTTP_CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
                            .addInterceptor(apikey)
                            .addInterceptor(loggingInterceptor)
                            .addNetworkInterceptor(new HttpCacheInterceptor())
                            .cache(cache)
                            .build();
                }
            }
        }
        return mOkHttpClient;
    }

    static class HttpCacheInterceptor implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if (!NetWorkUtil.isNetConnected(App.getAppContext())) {
                request = request.newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build();
                Log.d("Okhttp", "no network");
            }

            Response originalResponse = chain.proceed(request);
            if (NetWorkUtil.isNetConnected(App.getAppContext())) {
                //有网的时候读接口上的@Headers里的配置,你可以在这里进行统一的设置
                String cacheControl = request.cacheControl().toString();
                return originalResponse.newBuilder()
                        .header("Cache-Control", cacheControl)
                        .removeHeader("Pragma")
                        .build();
            } else {
                return originalResponse.newBuilder()
                        .header("Cache-Control", "public, only-if-cached, max-stale=2419200")
                        .removeHeader("Pragma")
                        .build();
            }
        }
    }
}

你可以在获取本地token的时候,当有的时候加上即可。
7月13日更新:
5.网上有很多在mvp的时候关于数据层的设计,我这边是添加了DataManager来管理app数据,在p层是不关心数据的来源,无论是网络的还是本地缓存的数据,这个设计参考了别的大神的实现。

/**
 * Created by wukewei on 16/7/12.
 * 这个类是管理app的数据来源无论从网络获取.内存.还是磁盘
 */
public class DataManager {

    private static Gson gson;
    private static RxBus rxBus;
    private static HotApi mHotApi;
    private static CacheLoader cacheLoader;

    private Handler mHandler;
    private DataManager() {}
    public static DataManager getInstance() {
        return DataManagerHolder.INSTANCE;
    }


    public static class DataManagerHolder {
        private final  static DataManager INSTANCE = new DataManager();
    }

    public void initService() {
        gson = new Gson();
        rxBus = RxBus.getDefault();
        cacheLoader = CacheLoader.getInstance(App.getAppContext());
        HandlerThread ioThread = new HandlerThread("IoThread");
        ioThread.start();
        mHandler = new Handler(ioThread.getLooper());
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                mHotApi = HotFactory.getHotApi();
            }
        });
    }


    /***
     * 获取分类的类型
     * @param
     * @param
     * @return
     */
    public List getTabs() {
        List tabs = new ArrayList<>();
        tabs.add("科技");
        tabs.add("美女");
        tabs.add("生活");
        tabs.add("娱乐");
        tabs.add("搞笑");
        tabs.add("宅男");
        return tabs;
    }

    /***
     * 获取列表
     * @param pn 页码
     * @param type 类别名称
     * @return
     */
    public Observable> getPopular(int pn, String type) {
        return mHotApi.getPopular(pn, Constants.PAGE_SIZE, type)
                .compose(SchedulersCompat.applyIoSchedulers())
                .compose(RxResultHelper.handleResult())
                .doOnNext(populars -> {
                    if (pn == 1) {
                        ListPopular popular = new ListPopular(populars);
                        cacheLoader.upNewData(type, popular);
                    }
                });
    }

    /***
     * 获取缓存信息 默认只缓存第一页
     * @param type 类别名称
     * @param
     * @return
     */
    public Observable> getCachePopular(String type) {
        NetworkCache networkCache = new NetworkCache() {
            @Override
            public Observable get(String key, Class cls) {
                return mHotApi.getPopular(1, Constants.PAGE_SIZE, type)
                        .compose(SchedulersCompat.applyIoSchedulers())
                        .compose(RxResultHelper.handleResult())
                        .flatMap(populars -> {
                            ListPopular popular = new ListPopular(populars);
                            return Observable.just(popular);
                        });
            }
        };

        return cacheLoader.asDataObservable(Constants.NEW_LIST + type, ListPopular.class, networkCache)
                .map(listPopular -> listPopular.data);
    }
}

记得在app的时候初始化,

public class App extends Application {

    private static App appContext;

    @Override
    public void onCreate() {
        super.onCreate();
        appContext = this;
        DataManager.getInstance().initService();
    }

    public static App getAppContext() {
        return appContext;
    }

}

这样在p中的使用如下

Subscription subscription = DataManager.getInstance().getPopular(pn, type)
                .subscribe(populars -> {
                    mView.showContent();
                    if (isRefresh()) {
                        if (populars.size() == 0) mView.showNotdata();
                        mView.addRefreshData(populars);
                    } else {
                        mView.addLoadMoreData(populars);
                    }
                }, throwable -> {
                    if (isRefresh())
                    mView.showError(ErrorHanding.handleError(throwable));
                    handleError(throwable);
                });
结束

本人对rxjava认识不够深入,还在不断的学习中,要是有什么错误之处还望指正。要是觉得对你有所帮助的话,欢迎Star。再次送上项目的github地址。

你可能感兴趣的:(MVP+Rxjava+Retrofit构建项目)