This document translates from –>why should we use RxJava on Android
In addition: slightly cooler one season
Another: Slightly cooler one season
Feel Rxjava recent wind, do not learn a bit embarrassed. Batting practice is also a beginner rxjava, also feel the code seems more complex more difficult to understand. Read a foreign language empathy, a simple translation. This article introduces the advantages of using Rxjava. But it may be necessary to have a little rxjava basis, it is recommended to take a look at the parabola of the classic masterpiece of writing.
-Gorgeous cutting line. The translation starts ———
Reactive Extensions (RX) is a series of interfaces and methods. Provides developers with an easy-to-understand and quick-to-maintain approach.
Rxjava is doing this, providing a range of tools to help you write clean code.
To be honest, I think the code written by Rxjava is very difficult to understand when I start. And the introduction of a library, simply to use such a new API, this bothered me. Later. I get it. In the traditional way of coding. As the app progresses, I need to refactor the code and repeat the boilerplate code over and over again. To meet the changing needs of users, it makes me miserable.
The amount of work I do, in fact, is to rewrite the relevant methods and interfaces, either because of changes in requirements (which are the original sins of the development of the murders between the products) or the need to change the presentation or to change the processing information data. This is crazy.
Other than that. Such code is often very time-consuming to understand by others to maintain.
For a chestnut: we need to get a list of data from a database of users and show it. We were able to query the database with the Asynctask background, and the results were presented to the UI adapter. Simple Demo Sample code:
Public class sampletask extends asynctask<void,void, List<Users>> { Private FinalSampleadapter Madapter; Public Sampletask(Sampleadapter Sampleadapter) {madapter = Sampleadapater; }@Override protectedList<users>Doinbackground(Void ... voids) {//fetch There results from the database and return them to the OnPostExecutelist<users> Users = Getusersfromdatabase ();returnUsers }@Override protected void OnPostExecute(list<users> Users) {Super. OnPostExecute (products);//Checking If there is users on the database if(Users = =NULL) {//no users, presenting a view saying there is No usersShowemptyusersmessageview ();return; } for(User user:users) {madapter.add (user); } madapter.notifydatasetchanged (); }}
Now that there is a new requirement to simply display the non-guest user, we are dealing with a conditional inference before adding to adapter, or changing the condition of the database query.
Moreover. You are also asked to obtain additional information from the database. Is it shown in this adapter with the user?
That's why we use Rxjava to pull us out of this quagmire. Change posture. Our RX code is like this (if you have learned how to use the RX base):
publicfetchUsersFromDatabase() { return Observable.create(new Observable.OnSubscribe<List<User>(){ @Override publicvoidcall(Subscriber<?
super List<User>> subscriber){ // Fetch information from database subscriber.onNext(getUserList()); subscriber.onCompleted(); } });}
Be called like this:
Fetchusersfromdatabase (). Subscribeon (Schedulers.io ())//will process Everything in a new thread. Observeon (Androidschedulers.mainthread ())//will Listen the results on the main thread. Subscribe (NewSubscriber<list<user>> () {@Override Public void oncompleted() { }@Override Public void OnError(Throwable e) { }@Override Public void OnNext(list<user> users) {//do Whatever you want with each user} });
Started to change demand, huh?
Why not show guests? Rxjava to filter out such uninvited guests in minutes:
Fetchusersfromdatabase (). Filter (NewFunc1<user, boolean> () {@Override PublicBooleanPager(User user) {//only return the users which is not guests return!user.isguest (); }}). Subscribeon (Schedulers.io ()). Observeon (Androidschedulers.mainthread ()). Subscribe (NewSubscriber<user> () {@Override Public void oncompleted() { }@Override Public void OnError(Throwable e) {/*check If there is any error while retrieving from database*/}@Override Public void OnNext(User user) {//do Whatever you want with each user} } );
The traditional way, even if it's a simple change. To maintain elegant interface programming, we also have to create new interfaces and refactor the code to implement filtering.
But using Rxjava to make it all elegant, we just need an observer to get all the information, so you can use these methods to filter out the data you want.
Maybe you'll say it again. OK, this is very good very easy to read structure. But that seems to make the code much more quantitative. Well is right, but this is the time for Retrolambda to shine, this library is compatible with the use of java8 lambda expressions, method references, and so on.
Help us simplify the code such as the following:
fetchUsersFromDatabase() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(value -> { //Do whatever with the value },error -> { //do something with in case of error } );
This problem is perfectly fixed, and then you start asking, I need to add additional query results with the user display in this adapter how to break. It's really not a good thing:
fetchUsersFromDatabase() .zipWith(fetchSomethingElseFromDatabase(), (users, somethingElse) -> { /*here combine users and something else into a new object*/ }) .subscribe( o -> { /*use the combine object from users and something else to fill the adapter */});
As above, we can easily combine other data found in the database with the users to show a adapter together. is not easier to maintain. Less code. Easy to read, clear?
If you want to learn more in-depth Rxjava can read the following article, I read the benefit.
[Partytricks with RxJava, Rxandroid & Retrolambda] (https://medium.com/p/1b06ed7cd29c)
In addition, this tutorial [tutorial] (https://gist.github.com/staltz/868e7e9bc2a7b8c1f754) also helped me to step on the Rxjava road very much.
Why we want to use Rxjava in Android