RxJava series of seven (best practices)

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/baron_leizhang/article/details/98872565

0?wx_fmt=jpeg

Foreword

The title of the party a little, in fact, not to mention what is the best practice. Some time ago the company implemented 996, so there is no time and energy to update the blog (Okay - I admit I am lazy ~). Therefore, this article is simply two examples presented RxJava use in a production environment. But each of the examples I have this blog entry accompanied by a complete code.

This issue is planned to introduce RxJava framework and design ideas, but considering Netflix will release the official version RxJava2.0 at the end of October; it was decided to RxJava framework analysis and design ideas put before making 2.0 official release . I will have a follow-up series of articles to introduce distinguish RxJava1.x and 2.x of.

Examples First, access to the App installed on your phone

The first example shows that we need a third party app on an Android device list of installed, on environment to build, depending on configuration, usage RecyclerView etc. I do not do these basic contents stated. You need to understand the students can go down the project on GitHub to clone look. Here I mainly talk about how to achieve the core functionality by RxJava.

We need to call the preferred system api to get all the installed app, so OnSubscribethe callmethod call getApplicationInfoList(). But the getApplicationInfoList()acquired data does not fully meet our business needs:

  1. Since we only need to show on mobile phones installed third-party App, and therefore need filterto filter out app system operators;

  2. ApplicationInfoWe need not type, by requiring mapthe operator to be converted AppInfo;

  3. Since the acquisition ApplicationInfo, data filtering, data conversion is relatively time consuming, and therefore we need subscribeOnto handle these operations into a series of sub-thread operator;

  4. To show the information related to the page in the UI operation, it is necessary by observeOnthe operator onNext, onCompleted, onErrordispatched to the main thread, then we update the UI in these methods.

Here is the core code:

final PackageManager pm = MainActivity.this.getPackageManager();Observable.create(new Observable.OnSubscribe<ApplicationInfo>() {        @Override        public void call(Subscriber<? super ApplicationInfo> subscriber) {            List<ApplicationInfo> infoList = getApplicationInfoList(pm);            for (ApplicationInfo info : infoList) {                subscriber.onNext(info);            }            subscriber.onCompleted();        }    }).filter(new Func1<ApplicationInfo, Boolean>() {        @Override        public Boolean call(ApplicationInfo applicationInfo) {            return (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0;        }    }).map(new Func1<ApplicationInfo, AppInfo>() {        @Override        public AppInfo call(ApplicationInfo applicationInfo) {            AppInfo info = new AppInfo();            info.setAppIcon(applicationInfo.loadIcon(pm));            info.setAppName(applicationInfo.loadLabel(pm).toString());            return info;        }    }).subscribeOn(Schedulers.io())    .observeOn(AndroidSchedulers.mainThread())    .subscribe(new Subscriber<AppInfo>() {        @Override        public void onCompleted() {            mAppListAdapter.notifyDataSetChanged();            mPullDownSRL.setRefreshing(false);        }        @Override        public void onError(Throwable e) {            mPullDownSRL.setRefreshing(false);        }        @Override        public void onNext(AppInfo appInfo) {            mAppInfoList.add(appInfo);        }    });

Program execution renderings:

0?wx_fmt=png

I put a complete code on GitHub, we are interested you can go to clone themselves run down look.

Source address: https: //github.com/BaronZ88/HelloRxAndroid

Example Two, RxJava + Retrofit2 achieve weather data acquisition

RxJava + Retrofit2 almost a standard Android application development, and in this case we have to talk about how the two are together with the help of our fast development.

Retrofit2 in a standard interface definition is as follows:

@GET("weather")Observable<Weather> getWeather(@Query("cityId") String cityId);

Now, with RxJava, a basic network request we will be able to achieve this:

ApiClient.weatherService.getWeather(cityId)                 .subscribeOn(Schedulers.io())                .observeOn(AndroidSchedulers.mainThread())                .subscribe(new Action1<Weather>() {                    @Override                    public void call(Weather weather) {                        weatherView.displayWeatherInformation(weather);                    }                });

But sometimes we do not know probably start cityId, we only know cityName. So we need to access the server, get cityId the corresponding city name, and then go get weather data through this cityId.

Similarly, we need to define a get cityId interface:

@GET("city")Observable<String> getCityIdByName(@Query("cityName") String cityName);

Then we will be able to realize the need to use the omnipotent RxJava.

ApiClient.weatherService.getCityIdByName("上海")             .flatMap(new Func1<String, Observable<Weather>>() {                 @Override                 public Observable<Weather> call(String cityId) {                     return ApiClient.weatherService.getWeather(cityId);                 }             }).subscribeOn(Schedulers.io())             .observeOn(AndroidSchedulers.mainThread())             .subscribe(new Action1<Weather>() {                 @Override                 public void call(Weather weather) {                     weatherView.displayWeatherInformation(weather);                 }             });

Wow! ~ So easy! ! ! My mother no longer have to worry about ....

Source address: https: //github.com/BaronZ88/MinimalistWeather

MinimalistWeather this project is still in development, this project not only includes the use RxJava and Retrofit, but also includes the use of MVP, ORMLite, RetroLambda, ButterKnife open source libraries, etc.

RxJava1.X series of articles to this end, due to my limited understanding of RxJava of this series of articles also please correct me if wrong. There are doubts in the use RxJava process also welcome to communicate with me. study together! Common progress!

Well, we RxJava2 see! ~


If you like this series of articles, I know almost welcome attention columns and GitHub.

  • Know almost Column: https: //zhuanlan.zhihu.com/baron

  • GitHub:https://github.com/BaronZ88


Guess you like

Origin blog.csdn.net/baron_leizhang/article/details/98872565