Why should we use RxJava in Android?

Source: Internet
Author: User

Why should we use RxJava in Android?

I feel sorry for the recent popularity of RxJava. I am also a beginner in RxJava. I also feel that the code is more complicated and difficult to understand. I have read a foreign article, and I have a simple translation. This article briefly introduces the advantages of RxJava. However, there may be a little RxJava Foundation. We recommend that you take a look at the Classic originality of the parabolic writing.
-- Gorgeous split line, Translation Start ---

Reactive Extensions (Rx) is a series of interfaces and methods that provide developers with an easy-to-understand and easy-to-maintain method. RxJava is doing this. It provides a series of tools to help you write concise code.
To be honest, at first I thought the code written by RxJava was very difficult to understand and introduced a library, just to use this new api, which bothered me. Later, I understood. With the traditional coding method and the development of the app, I Need To refactor the code and repeat the sample code once and again to meet the new needs of users, which makes me miserable.
I have done a lot of work, in fact, to rewrite the relevant methods and interfaces, is because of the changes in demand (this is the original sin of the bloody cases between development and products) you can change the information you want to display or the information you want to process .. this is crazy. In addition, this type of code is usually time-consuming for other maintenance personnel to understand.
For example, we need to obtain and display the Linked List data of a group of users from the database. We can use AsyncTask to query the database in the background and display the results to the Ui adapter. Simple sample code:
public class SampleTask extends AsyncTask
  
   > {    private final SampleAdapter mAdapter;    public SampleTask(SampleAdapter sampleAdapter) {        mAdapter = sampleAdapater;    }    @Override    protected List
   
     doInBackground(Void... voids) {        //fetch there results from the database and return them to the onPostExecute        List
    
      users = getUsersFromDatabase();        return users;    }    @Override    protected void onPostExecute(List
     
       users) {        super.onPostExecute(products);        // Checking if there are users on the database        if(users == null) {            //No users, presenting a view saying there are no users            showEmptyUsersMessageView();            return;        }        for(User user : users){            mAdapter.add(user);        }        mAdapter.notifyDataSetChanged();    }}
     
    
   
  

Now we have a new requirement that only non-guest users be displayed. The solution is to add a condition before the adapter to determine whether it is a guset or to change the database query conditions. What's more, are you asked to obtain other information from the database and display it in the adapter together with the user?
That's why we use RxJava.And pull us out of this quagmire. In another way, the Rx code is like this (assuming you have learned basic Rx usage ):

public Observable
  
   
    
     
      
       > fetchUsersFromDatabase() { return Observable.create(new Observable.OnSubscribe
       
        (){ @Override public void call(Subscriber> subscriber){ // Fetch information from database subscriber.onNext(getUserList()); subscriber.onCompleted(); } });}
       
      
     
    
   
  

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(new Subscriber
  
   
    
     
      
       
        
         >() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(List
         
           users) { //Do whatever you want with each user } });
         
        
       
      
     
    
   
  

I started to change the requirements.
Why not show guests? RxJava will filter out the uninvited customers in minutes:

fetchUsersFromDatabase()        .filter(new Func1
  
   
    
     
      
       
        
         
          
           () { @Override public Boolean call(User user) { //only return the users which are not guests return !user.isGuest(); } }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber
           
            () { @Override public void onCompleted() { } @Override public void onError(Throwable e) { /*Check if there was any error while retrieving from database*/ } @Override public void onNext(User user) { //Do whatever you want with each user } } );
           
          
         
        
       
      
     
    
   
  

In the traditional way, even for a simple change, to maintain elegant interface-based programming, we also need to create new interfaces and refactor the code to implement filtering. But with RxJava, this becomes more elegant. We only need one observer to get all the information, so that you can use it as much as possible.MethodTo filter and obtain the desired data.
Maybe you will say again, OK, this is a very good and easy-to-read structure, but it seems to make the amount of code more. Well you are right, but this is the time for lambda to shine. This library is compatible with Java 8 lambda expressions, method references, and so on.
The code is simplified as follows:

fetchUsersFromDatabase()        .subscribeOn(Schedulers.io())        .observeOn(AndroidSchedulers.mainThread())        .subscribe(value -> {                    //Do whatever with the value                },error -> {                    //do something with in case of error                }        );

The problem was solved perfectly, and you started to ask again. I need to add other query results and how to break them in the adapter together with the user. This is really not the case:

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 shown above, we can easily combine other data found by the database with users to display it together with an adapter. Is it easier to maintain, less code, easier to read, and clearer?

Related Article

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.