Why we want to use Rxjava in Android

Source: Internet
Author: User

This document translates from –>why should we use RxJava on Android
In addition: slightly cooler one season
Another: Slightly cooler one season

Feel Rxjava recently, do not learn a bit embarrassed, batting practice is also a beginner Rxjava, also feel code seems more complex more difficult to understand, read a foreign empathy, simple translation. This article briefly describes 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.
--Ornate split line, translation start ———

The reactive Extensions (RX) is a series of interfaces and methods that provide developers with an easy-to-understand, fast and easy-to-maintain approach. Rxjava is doing this, providing a range of tools to help you write clean code.
To be honest, at first I thought the code written by Rxjava was difficult to understand and introduced a library that bothered me by simply using this new kind of API. Later, I understand. In the traditional coding, with the development of the app, I need to refactor the code, repeat the boilerplate code again and again to meet the new needs of the user constantly changing, which makes me miserable.
I do a lot of work, in fact, is to rewrite the relevant methods and interfaces, that is, because of changes in demand (this is the original crime of development and product of the murders) or need to change the display of information or need to change processing information data. It's crazy. In addition, this code is often time-consuming to understand for others to maintain.
For a chestnut: we need to get a list of the list of users from the database and show it. We can use Asynctask to query the database, the results obtained to the UI of the adapter display. Simple 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 display only non-guest user, we are dealing with a condition that is not guset before adding to adapter, or changing the condition of the database query. What's more, you're being asked to get additional information from the database, as shown in this adapter with user?
That's why we use Rxjava to pull us out of this quagmire. In a different posture, our RX code is like this (assuming you have learned the RX base usage):

publicfetchUsersFromDatabase() {    return Observable.create(new Observable.OnSubscribe<List<User>(){        @Override        publicvoidcallsuper 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}        });

It's starting to change demand, huh?
How do not show guests, Rxjava minute to filter out this intruder:

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 is a simple change, in order to maintain elegant interface programming, we have to create a new interface, refactoring 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.
You may say again, OK, this is a very good, easy-to-read structure, but it 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 as follows:

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 perfect, and then you start to ask, I need to add additional query results with the user show in this adapter how broken. 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 it easier to maintain, less code, easier to read, clearer?
If you want to learn more in-depth Rxjava can read the following article, I look after 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 a lot.

Why we want to use Rxjava in Android

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.