菜单

实战知识梳理

2019年4月3日 - 注册免费送38元体验金

福特ExplorerxJava二 实战连串作品

中华VxJava二 实战知识梳理(壹) – 后台执行耗费时间操作,实时通报 UI
更新

PRADOxJava二 实战知识梳理(二) –
总计一段时间内数据的平均值

牧马人xJava贰 实战知识梳理(三) –
优化搜索联想成效

PAJEROxJava贰 实战知识梳理(四) – 结合 Retrofit
请求新闻资讯

QashqaixJava2 实战知识梳理(五) –
简单及进阶的轮询操作

ENCORExJava2 实战知识梳理(六) –
基于错误类型的重试请求

QashqaixJava2 实战知识梳理(柒) – 基于 combineLatest
达成的输入表单验证

汉兰达xJava二 实战知识梳理(8) – 使用 publish + merge
优化先加载缓存,再读取互联网数据的伸手进度

RxJava二 实战知识梳理(九) – 使用 timer/interval/delay
达成职务调度

TiguanxJava二 实战知识梳理(十) – 显示屏旋转导致 Activity
重建时上升职务

HummerH二xJava2 实战知识梳理(1一) –
检查测试互连网状态并自动重试请求

科雷傲xJava二 实战知识梳理(1贰) – 实战讲解 publish & replay & share & refCount
& autoConnect

LacrossexJava2 实战知识梳理(一三) –
怎样使得错误发生时不自行终止订阅关系

景逸SUVxJava贰 实战知识梳理(14) – 在 token 过期时,刷新过期 token
并重复发起呼吁

XC90xJava二 实战知识梳理(一5) – 达成四个粗略的 MVP + SportagexJava + Retrofit
应用


一、前言

不知不觉,从七月二⑩七号的率先篇教程 LANDxJava2 实战知识梳理(一) –
后台执行耗费时间操作,实时通报 UI
更新

到明日刚好多少个礼拜,这一多重教程的指标根本是指望通过有个别实在的案例,让我们对此RxJava中的1些操作符能有相比直观的认识。

明天那篇作品,是后日早晨花了多少个钟头,对品种中用到的MVP + RxJava + Retrofit的漫天框架结构做了八个简化,抽离出里面最基本的壹部分编写制定的读取
Gank
中拉取音信托投资源新闻的例证。

该例子的源码能够透过
RxSample
的第七伍章获取,上边大家先介绍二个1体例子的框架:

注册免费送38元体验金 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来促成,有亟待明白的同校能够参见前边的那篇文章
奥迪Q5xJava贰 实战知识梳理(四) – 结合 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.壹 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层定义了三个接口,它们的意思分别为:

Presenter层则承担在View层发起呼吁之后,调用Model层获取数据,然后回调View层的接口举办界面的革新,因此它提供了三个接口:

3.2 View 层实现

那边,大家完毕Activity作为View注册免费送38元体验金,层的贯彻,它在有新的资讯列表回来时,文告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层分裂的接口举行拍卖,并且在数码重回时,将其和当前的数目开始展览统1,再通报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() {}
    }
}

此地我们所以要定义二个刷新类型的目的在于,在实际项目中,我们有以下二种刷新情势:

那里为了演示方便大家只兑现了前二种办法,大家随后在处理时,也足以借鉴相应的办法。

四、示例

下边,大家演示一下,先在联网状态下拉取资源音讯,再在断网情形下重新进入,读取缓存的事态:

注册免费送38元体验金 2

这篇小说原理的事物不多,因为信任咱们对此MVP也早就很熟练,首即便透过八个简便的案例演示三个什么在MVP架构个中使用RxJava,有1对未有贴出来的代码大家能够查看
RxSample
中的第十5章。


更加多小说,欢迎访问小编的 Android 知识梳理体系:

相关文章

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图