RxJava 1.x Understanding-3

Source: Internet
Author: User
Tags ming string format

In RxJava 1.x Understanding-1, we talked about the simple use of RxJava, but that's not enough because

The input data---> is manipulated by listeners (feeds), or the response is processed and the new data is generated, or events are sent to listeners--listeners execute their own methods.

The Rxjava can also transform the input data, generating new data (which can be complex data) rather than simple event triggering.

First, the provision of data, Advanced: RxJava just use
 /**   * RxJava just using * just--or using Create method  */ private  void   Rxjavajust () {log.d (TAG, "-----------just---------        "); Observable. Just ( "just 1", "Just 2", "Just 3"  new  action1<string> () { @Override  public  void   call (String s) {log.d (TAG,  "Item:" + s);    }                }); }

Just will continuously just the variable parameter data 1; just 2; just 3 .... Send it out

RxJava from use
    /*** RxJava from using * from--to or using the Create method*/    Private voidRxjavafrom () {log.d (TAG,"-----------from---------"); String[] Names= {"1", "2", "3"}; Observable.from (names). Subscribe (NewSubscriber<string>() {@Override Public voidOnNext (String s) {log.d (TAG,"Item:" +s); } @Override Public voidoncompleted () {log.d (TAG,"Completed!"); } @Override Public voidOnError (Throwable e) {log.d (TAG,"Error!");        }                }); LOG.D (TAG,"-----------from2---------"); //Simply put, the data is provided, and it is provided, and as for how to execute it, it is the observer's own business. Observable.from (names). Subscribe (NewAction1<string>() {@Override Public voidCall (String s) {log.d (TAG,"Item:" +s);    }                }); }

The from will continually send data from the array or collection

Data Transformation Rxjava Map transformation
    /*** Rxjava Map Transform * Convert type to another type*/    Private voidRxjavamap () {log.d (TAG,"-----------Map---------"); Observable.just ("1")//input type String                . Map(NewFunc1<string, integer>() {@Override PublicInteger Call (String s) {returnInteger.parseint (s); }}). Subscribe (NewAction1<integer>() {@Override Public voidCall (Integer integer) {log.d (TAG,"Item:" + integer + "Execute call Get thread ID:" +Thread.CurrentThread (). GetId ());    }                }); }
Observable.just ("999", "11")//input type String                . Map(NewFunc1<string, list<integer>>() {@Override PublicList<integer>Call (String s) {List<Integer> ints =NewArraylist<>();                        Ints.add (Integer.parseint (s));                        Ints.add (Integer.parseint (s));                        Ints.add (Integer.parseint (s)); returnints; }}). Subscribe (NewAction1<list<integer>>() {@Override Public voidCall (list<integer>integers) {                inti = 0; //here to traverse                 for(Integer integer:integers) {log.e (TAG,"Item" + i + ":" + +integer); I+ = 1;    }            }        }); }

You can see that the data in string format is converted to data in Integer format, or data in string format is converted to list<integer> format. Map is a one-to-one transformation.

Rxjava FlatMap Transform
    /*** Rxjava FlatMap Transform * Event Redistribution: * * from the above code, it can be seen that flatMap () and map () have a common point: it is also the conversion of the parameters passed in after the return of another object.     * But note that unlike map (), FlatMap () returns a Observable object, but the Observable object is not sent directly to the Subscriber callback method. * The principle of flatMap () is this: * 1. Creates a Observable object using the incoming event object; * 2. Does not send this Observable, but activates it, so it starts sending events; * 3.     Each created Observable event is sent to the same Observable, and this Observable is responsible for unifying the events to Subscriber's callback method. * These three steps, which split the event into level two, were distributed through a unified path after the initial object was "flattened" by a newly created set of Observable.     And this "flattening" is flatMap () the so-called flat. */    Private voidRxjavaflatmap () {log.d (TAG,"-----------Rxjavaflatmap---------"); List<Student> students =NewArraylist<>(); List<Source> sources =NewArraylist<>(); Sources.add (NewSource (1, "chemistry", 80)); Sources.add (NewSource (2, "physical", 79)); Sources.add (NewSource (3, "creature", 78)); Students.add (NewStudent ("Xiao Ming 1", 1, sources)); Students.add (NewStudent ("Xiao Ming 2", 1, sources)); Observable.from (students) . FlatMap(NewFunc1<student, observable<source>>() {@Override PublicObservable<source>Call (Student Student) {log.d (TAG,"Item:" +student.name); returnObservable.from (student.msources); }}). Subscribe (NewAction1<source>() {@Override Public voidCall (source source) {LOG.D (TAG,"Item:" + source + "Execute call to get thread ID:" +Thread.CurrentThread (). GetId ());    }                }); }
 //------------------------The class used for the test-----------------------------    classStudent {String name;//Student Name        intID; List<Source> msources;//all courses for each student         PublicStudent (String name,intID, list<source>sources) {             This. Name =name;  This. ID =ID; Msources=sources; } @Override PublicString toString () {return"student{" + "name=" + name + ' \ ' + ", id=" + ID + ", msources= "+ Msources + '} '; }    }    classSource {intSourceID;//IDString name;//Course Name        intScore;//Achievements         PublicSource (intSourceID, String name,intscore) {             This. SourceID =SourceID;  This. Name =name;  This. score =score; } @Override PublicString toString () {return"source{" + "sourceid=" + SourceID + ", name= '" + name + "\" + " , score= "+ Score + '} '; }    }

Output Result:

 02-09 15:45:50.580 3223-3223/pers.bolin.rxjavademo d/mainactivity:item: Xiao Ming 1  02-09 15:45:50.581 3223-3223/pers.bolin.rxjavademo d/mainactivity:item:source{sourceid=1, name= ' chemistry ', score= 80} Execute call get thread id:202-09 15:45:50.581 3223-3223/pers.bolin.rxjavademo d/mainactivity:item:source{sourceid=2, name= ' physical ' , score=79} executes the call to get thread id:202-09 15:45:50.582 3223-3223/pers.bolin.rxjavademo d/mainactivity:item:source{sourceid=3, Name= ' mobs ', score=78} Execute call get thread id:202-09 15:45:50.582 3223-3223/pers.bolin.rxjavademo d/ Mainactivity:item: Xiaoming 2  02-09 15:45:50.582 3223-3223/pers.bolin.rxjavademo d/mainactivity:item:source{ Sourceid=1, Name= ' chemistry ', score=80} execute call to get thread id:202-09 15:45:50.582 3223-3223/pers.bolin.rxjavademo d/mainactivity:item: source{sourceid=2, name= ' physical ', score=79} Execute call get thread id:202-09 15:45:50.583 3223-3223/pers.bolin.rxjavademo D/ mainactivity:item:source{sourceid=3, name= ' creature ', score=78} execute call to get thread Id:2 

In fact, the above code can also be implemented with map:

Observable.from (students). Map (NewFunc1<student, list<source>>() {@Override PublicList<source>Call (Student Student) {log.d (TAG,"Item:" +student.name); returnstudent.msources; }}). Subscribe (NewAction1<list<source>>() {@Override Public voidCall (list<source>sources) {                //The main difference here is that we did a loop traversal ourselves. Instead of Flatmap, the Source object is directly obtained, not the List<source> object                 for(Source source:sources) {log.d (TAG,"Item:" + source + "Execute call to get thread ID:" +Thread.CurrentThread (). GetId ()); }            }        });

FlatMap () has a common point with map (): It also converts the passed-in parameter to return another object.
However, it is important to note that unlike map (), FlatMap () returns a Observable object, but the Observable object is not sent directly to the Subscriber callback method.
The principle of flatMap () is this:
1. Create an Observable object using the incoming event object;
2. Do not send this Observable, but activate it, so it starts sending events;
3. Every event sent by the created Observable is remitted to the same Observable, and this Observable is responsible for unifying the events to Subscriber's callback method.
In these three steps, the event was split into level two and distributed through a unified path after the initial object was "flattened" by a newly created set of Observable. And this "flattening" is flatMap () the so-called flat.

Summary: The role of Rxjava is
For data: Transform the input data into the desired data, and you can specify the thread of execution to get the final result.
For events: Trigger event, observer perception, Observer performs an action, and can specify the thread to execute.

Resources:

To build a Rxjava, uncover the principles of Rxjava's realization

RxJava for Android Developers

RxJava 1.x Understanding-3

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.