RxJava2 实战系列文章

RxJava2 实战知识梳理(1) – 后台执行耗时操作,实时通报 UI
更新
RxJava2 实战知识梳理(2) –
计算一段时间内数据的平均值
RxJava2 实战知识梳理(3) –
优化搜索联想功能
RxJava2 实战知识梳理(4) – 结合 Retrofit
请求新闻消息
RxJava2 实战知识梳理(5) –
简单和进阶的轮询操作
RxJava2 实战知识梳理(6) –
基于左类型的重试请求
RxJava2 实战知识梳理(7) – 基于 combineLatest
实现之输入表单验证
RxJava2 实战知识梳理(8) – 使用 publish + merge
优化先加载缓存,再念博网络数据的请过程
RxJava2 实战知识梳理(9) – 使用 timer/interval/delay
实现任务调度
RxJava2 实战知识梳理(10) – 屏幕旋转导致 Activity
重建时回升任务
RxJava2 实战知识梳理(11) –
检测网络状态并活动重试请求
RxJava2 实战知识梳理(12) – 实战讲解 publish & replay & share & refCount
& autoConnect
RxJava2 实战知识梳理(13) –
如何让错误有时不自动停止订阅关系
RxJava2 实战知识梳理(14) – 在 token 过期时,刷新过期 token
并再发起呼吁
RxJava2 实战知识梳理(15) – 实现一个概括的 MVP + RxJava + Retrofit
应用


一、前言

不知不觉,从八月二十七号的第一篇教程 RxJava2 实战知识梳理(1) –
后台执行耗时操作,实时通报 UI
更新
到今天恰好有限独礼拜,这同一多元教程的目的关键是要经过有其实的案例,让大家对此RxJava遭受的组成部分操作符能有于直观的认。

今随即篇稿子,是昨天晚上花了几乎独小时,对项目遭到因故到之MVP + RxJava + Retrofit的上上下下架构做了一个简化,抽离出中最基本的一部分编制的读取
Gank
中拉取新闻资讯的例子。

拖欠例子的源码可以透过
RxSample
的第十五回获取,下面我们先行介绍一个全例子的框架:

新濠娱乐 1

二、Model

Model针对许高达图被之NewsRepository,它肩负为Presenter臃肿提供数据,因为数量发生或来缓存或者网络,因此于NewsRepository未遭含了个别独数据源,也便是LocalNewsSourceRemoteNewsSource

public class NewsRepository {

    private LocalNewsSource mLocalNewsSource;
    private RemoteNewsSource mRemoteNewsSource;

    private NewsRepository() {
        mLocalNewsSource = new LocalNewsSource();
        mRemoteNewsSource = new RemoteNewsSource();
    }

    public static NewsRepository getInstance() {
        return Holder.INSTANCE;
    }

    private static class Holder {
        private static NewsRepository INSTANCE = new NewsRepository();
    }

    public Observable<NewsEntity> getNetNews(String category) {
        return mRemoteNewsSource.getNews(category).doOnNext(new Consumer<NewsEntity>() {
            @Override
            public void accept(NewsEntity newsEntity) throws Exception {
                mLocalNewsSource.saveNews(newsEntity);
            }
        });
    }

    public Observable<NewsEntity> getCacheNews(String category) {
        return mLocalNewsSource.getNews(category);
    }

}

2.1 LocalNewsSource

LocalNewsSource由此数据库的主意实现了情报的缓存,该数据库的说明包含两独字段,即资讯的归类,和情报的切实可行多少。

public class LocalNewsSource {

    private static final String[] QUERY_PROJECTION = new String[] { NewsContract.NewsTable.COLUMN_NAME_DATA };
    private static final String QUERY_SELECTION = NewsContract.NewsTable.COLUMN_NAME_CATEGORY + "= ?";

    private NewsDBHelper mNewsDBHelper;
    private SQLiteDatabase mSQLiteDatabase;

    public LocalNewsSource() {
        mNewsDBHelper = new NewsDBHelper(Utils.getAppContext());
        mSQLiteDatabase = mNewsDBHelper.getWritableDatabase();
    }

    public Observable<NewsEntity> getNews(String category) {
        return Observable.just(category).flatMap(new Function<String, ObservableSource<NewsEntity>>() {
            @Override
            public ObservableSource<NewsEntity> apply(String category) throws Exception {
                NewsEntity newsEntity = new NewsEntity();
                Cursor cursor = mSQLiteDatabase.query(NewsContract.NewsTable.TABLE_NAME, QUERY_PROJECTION, QUERY_SELECTION, new String[] { category }, null, null, null);
                if (cursor != null && cursor.moveToNext()) {
                    String data = cursor.getString(cursor.getColumnIndex(NewsContract.NewsTable.COLUMN_NAME_DATA));
                    newsEntity = JSON.parseObject(data, NewsEntity.class);
                }
                if (cursor != null) {
                    cursor.close();
                }
                return Observable.just(newsEntity);
            }
        });
    }


    public void saveNews(NewsEntity newsEntity) {
        Observable.just(newsEntity).observeOn(Schedulers.io()).subscribe(new Consumer<NewsEntity>() {

            @Override
            public void accept(NewsEntity newsEntity) throws Exception {
                if (newsEntity.getResults() != null && newsEntity.getResults().size() > 0) {
                    String cache = JSON.toJSONString(newsEntity);
                    ContentValues values = new ContentValues();
                    values.put(NewsContract.NewsTable.COLUMN_NAME_CATEGORY, "Android");
                    values.put(NewsContract.NewsTable.COLUMN_NAME_DATA, cache);
                    mSQLiteDatabase.insert(NewsContract.NewsTable.TABLE_NAME, null, values);
                }
            }
        });
    }
}

2.2 RemoteNewsSource

RemoteNewsSource虽承担从网络上拉取资讯信息,这里用了Retrofit来兑现,有需要了解的同班可以参见前的即刻篇稿子
RxJava2 实战知识梳理(4) – 结合 Retrofit
请求新闻资讯。

public class RemoteNewsSource {

    private NewsApi mNewsApi;

    public RemoteNewsSource() {
        mNewsApi = new Retrofit.Builder()
                .baseUrl("http://gank.io")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build().create(NewsApi.class);
    }

    public Observable<NewsEntity> getNews(String category) {
        return mNewsApi.getNews(category, 10, 1);
    }

}

三、View 和 Presenter

3.1 View 和 Presenter 的接口定义

率先,我们要对此ViewPresenter期间的互相定义接口,这些接口我们形容于NewsMvpContract中:

public class NewsMvpContract {

    public static final int REFRESH_AUTO = 0;
    public static final int REFRESH_CACHE = 1;

    @IntDef ({REFRESH_AUTO, REFRESH_CACHE})
    public @interface RefreshType {}

    public interface View {
        void onRefreshFinished(@RefreshType int refreshType, List<NewsBean> newsEntity);
        void showTips(String message);
    }

    public interface Presenter {
        void refresh(@RefreshType int refreshType);
        void destroy();
    }

}

View臃肿定义了简单只接口,它们的义分别吗:

  • onRefreshFinished:刷新资讯列表。
  • showTips:在生误时与用户提示。

Presenter臃肿则负责在View臃肿发起呼吁后,调用Model臃肿获取数据,然后回调View臃肿的接口进行界面的翻新,因此她提供了片独接口:

  • refresh:用于View臃肿发起刷新操作。
  • destroy:在View臃肿销毁时,取消订阅。

3.2 View 层实现

此地,我们兑现Activity作为View臃肿的贯彻,它当起新的消息列表回来时,通知RecyclerView进展刷新,而用提醒时虽经过SnackBar展开提醒,同时其还拥有一个NewsPresenter的实例,并在销毁时调用它的destroy方取消订阅。

public class NewsMvpActivity extends AppCompatActivity implements NewsMvpContract.View {

    private CoordinatorLayout mRootLayout;
    private RecyclerView mRecyclerView;
    private NewsMvpAdapter mRecyclerAdapter;
    private List<NewsBean> mNewsBeans = new ArrayList<>();
    private NewsMvpContract.Presenter mPresenter;
    private LinearLayoutManager mLayoutMgr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_mvp);
        initView();
        dispatchRefresh(NewsMvpContract.REFRESH_CACHE);
    }

    private void initView() {
        mRootLayout = (CoordinatorLayout) findViewById(R.id.cl_root);
        mRecyclerView = (RecyclerView) findViewById(R.id.rv_news);
        mRecyclerAdapter = new NewsMvpAdapter();
        mRecyclerAdapter.setNewsResult(mNewsBeans);
        mLayoutMgr = new LinearLayoutManager(this);
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        mRecyclerView.setLayoutManager(mLayoutMgr);
        mRecyclerView.setAdapter(mRecyclerAdapter);
        mPresenter = new NewsPresenter(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        dispatchRefresh(NewsMvpContract.REFRESH_AUTO);
    }

    private void dispatchRefresh(@NewsMvpContract.RefreshType int refreshType) {
        mPresenter.refresh(refreshType);
    }

    @Override
    public void onRefreshFinished(@NewsMvpContract.RefreshType int refreshType, List<NewsBean> newsBeans) {
        mNewsBeans.clear();
        mNewsBeans.addAll(newsBeans);
        mRecyclerAdapter.notifyDataSetChanged();
    }

    @Override
    public void showTips(String message) {
        Snackbar.make(mRootLayout, message, Snackbar.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.destroy();
    }
}

3.3 Presenter 层实现

Presenter臃肿是比较复杂的地方,当View层调用refresh接口时,它需要基于刷新的品种,请求Model臃肿不同的接口进行拍卖,并且以数据返回时,将那个及当下的数量进行统一,再通报View臃肿开展刷新。

public class NewsPresenter implements NewsMvpContract.Presenter {

    private static final long AUTO_REFRESH_TIME = 1000 * 60 * 10;
    private CompositeDisposable mCompositeDisposable;
    private NewsMvpContract.View mView;
    private List<NewsBean> mNewsBeans;
    private long mLastNetUpdateTime;

    public NewsPresenter(NewsMvpContract.View view) {
        mView = view;
        mCompositeDisposable = new CompositeDisposable();
        mNewsBeans = new ArrayList<>();
    }

    @Override
    public void refresh(@RefreshType int refreshType) {
        if (refreshType == NewsMvpContract.REFRESH_CACHE) {
            NewsRepository.getInstance()
                    .getCacheNews("Android")
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new RefreshObserver(refreshType));
        } else {
            if (System.currentTimeMillis() - mLastNetUpdateTime > AUTO_REFRESH_TIME) { //自动刷新的间隔时间为十分钟。
                NewsRepository.getInstance()
                        .getNetNews("Android")
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new RefreshObserver(refreshType));
            }
        }
    }

    @Override
    public void destroy() {
        mCompositeDisposable.clear();
        mView = null;
    }

    private void updateNewsBeans(@NewsMvpContract.RefreshType int refreshType, NewsEntity newsEntity) {
        List<NewsBean> filter = new ArrayList<>();
        for (NewsResultEntity resultEntity : newsEntity.getResults()) { //对资讯进行去重,需要重写NewsBean的对应方法。
            NewsBean newsBean = entityToBean(resultEntity);
            if (!mNewsBeans.contains(newsBean)) {
                filter.add(newsBean);
            }
        }
        if (refreshType == NewsMvpContract.REFRESH_CACHE && mNewsBeans.size() == 0) { //只有当前没有数据时,才使用缓存。
            mNewsBeans = filter;
        } else if (refreshType == NewsMvpContract.REFRESH_AUTO) { //自动刷新的数据放在头部。
            mNewsBeans.addAll(0, filter);
            mLastNetUpdateTime = System.currentTimeMillis();
        }
    }

    private NewsBean entityToBean(NewsResultEntity resultEntity) {
        String title = resultEntity.getDesc();
        NewsBean bean = new NewsBean();
        bean.setTitle(title);
        return bean;
    }

    private class RefreshObserver extends DisposableObserver<NewsEntity> {

        private @NewsMvpContract.RefreshType int mRefreshType;

        RefreshObserver(@NewsMvpContract.RefreshType int refreshType) {
            mRefreshType = refreshType;
        }

        @Override
        public void onNext(NewsEntity newsEntity) {
            updateNewsBeans(mRefreshType, newsEntity);
            mView.onRefreshFinished(mRefreshType, mNewsBeans);
        }

        @Override
        public void onError(Throwable throwable) {
            mView.showTips("刷新错误");
        }

        @Override
        public void onComplete() {}
    }
}

此间我们就此要定义一个刷新类型的目的在,在事实上项目遭到,我们发以下几种植刷新方式:

  • 读取缓存:只在列表为空时才增长。
  • 机关刷新:需要依据时间判定,每隔10分钟进入同一赖界面后自动获得。
  • 下拉刷新:将数据上加于脑袋。
  • 上拉刷新:将数据上加于尾部。

此以演示方便我们仅仅兑现了前少种植艺术,大家随后当处理常,也足以借鉴相应的法。

四、示例

下面,我们演示一下,先以联网状态下拉取资讯,再以断网情况下再进入,读取缓存的状态:

新濠娱乐 2

当时首文章原理的东西不多,因为信任大家对MVP啊曾十分熟稔,主要是经一个概括的案例演示一个哪些当MVP搭当中以RxJava,有局部没贴出来的代码大家可以查
RxSample
中的第十五段。


再也多篇,欢迎访问我的 Android 知识梳理系列:

  • Android
    知识梳理目录:http://www.jianshu.com/p/fd82d18994ce
  • 个人主页:http://lizejun.cn
  • 个体文化总结目录:http://lizejun.cn/categories/
网站地图xml地图