Combination of rxjava-operators observable

Source: Internet
Author: User
Tags emit throwable


In the actual development process, a function is implemented, which needs to be handled by multiple threads. For example, room temperature monitors need to monitor the temperature of different rooms, and the temperature sensor is transferred and saved to the database in real time, which means we need to handle multiple observables. In this case, what should we do with these observables? In this blog, we'll learn about combining operators to learn how to work with multiple observables at the same time to create the observable we want.

MergeThe merge operator merges two or more observables into a single emitted data item and launches it.
The flowchart for the merge operator is as follows:

Example code:
        list<student> list_0 = new arraylist<> ();        list<student> list_1 = new arraylist<> ();        List_0.add (New Student ("Merge-a11", "20", "1101"));        List_0.add (New Student ("Merge-a12", "23", "1102"));        List_0.add (New Student ("Merge-a13", "22", "1103"));        List_0.add (New Student ("Merge-a14", "21", "1104"));        List_0.add (New Student ("Merge-a15", "20", "1105"));        List_1.add (New Student ("Merge-b11", "20", "1101"));        List_1.add (New Student ("Merge-b12", "23", "1102"));        List_1.add (New Student ("Merge-b13", "22", "1103"));        observable<student> obs_0 = Observable.from (LIST_0);        observable<student> obs_1 = Observable.from (list_1);        observable<student> Obsmerge = Observable.merge (Obs_0, obs_1); Obsmerge.subscribe (New observer<student> () {@Override public void oncompleted              () {} @Override      public void OnError (Throwable e) {} @Override public void                    OnNext (Student Student) {madastu.adddata (Student); }                });



As the sample code, we created two observable data lists Obs_0 and Obs_1, using Observable.merge (), merging Obs_0 and Obs_1, and creating a new observables list Obsmerge, It emits all the data emitted by the source observables in a single observable sequence.

Note: When a new observables is launched, it can be considered that any observable error will break the merge. If you want to avoid this, you can call the Mergedelayerror () method to indicate that it can continue to emit data from a single observable, that is, one of them throws an error. When all the observables are complete, mergedelayerror () will emit onerror ().

ZipThe zip operation conforms to the data items emitted by two or more observables, transforms them according to the specified function func*, and emits a new value.
The flowchart of the zip operator is as follows:

Example code:
observable<student> Obs_stu = Observable.from (mlists);    observable<long> Obs_long = observable.interval (1, timeunit.seconds); Observable.zip (Obs_stu, Obs_long, New func2<student, Long, student> () {@Override public stude            NT Call (Student Student, Long along) {return Updatetitle (Student, along); }}). Observeon (Androidschedulers.mainthread ()). Subscribe (New observer<student> () {@Overr             IDE public void oncompleted () {} @Override public void OnError (Throwable e) { } @Override public void OnNext (Student Student) {madastu.adddata (Student            );           }        });        Private Student Updatetitle (Student Stu, Long time) {Stu.setname (time + "-" + stu.getname ());    return Stu; }



From the zip operator flowchart and the sample code, it is clear that the zip will observables the list obs_stu and obs_long data in the function func by calling
Updatetitle (Student Stu, Long time) method, merges and launches the value one by one of the two list.
The ZIP function has three key parameters: two observables and one func. In fact, two observables is the observable data source, and the Func method is used to merge and emit two observables under the corresponding rules.
JoinThe join operator is also the result of the two observable resulting in merging, the result of which is a new observable, but the join operator can control the life cycle of each observable result, and within the life cycle of each result, Can be combined with the results of another observable according to certain rules.
Join operator Flowchart:

Example code:
    observable<student> Obs_stu = observable.interval (1, timeunit.seconds). Map (new Func1<long, Student&gt ;() {@Override public Student call (Long along) {return Mlists.get (Along.intvalue ())            ;    }        });    observable<long> obs_time = observable.interval (1, timeunit.seconds); Obs_stu.join (Obs_time, Student-Observable.timer (2,timeunit.seconds), Time-observable.int            Erval (2, Timeunit.seconds), This::updatetitle). Observeon (Androidschedulers.mainthread ())                . Subscribe (New observer<student> () {@Override public void oncompleted () { } @Override public void OnError (Throwable e) {} @Overrid                    e public void OnNext (Student Student) {madastu.adddata (Student);                  Mlistsadd.add (student);  int position = Mlistsadd.size ()-1;                    Madastu.adddatabyposition (position, student);                Rvcombining.smoothscrolltoposition (position); }            });

As you can see from the above code, the join process:
1. Define the data source: source observable sequence Obs_stu will emit a data source every 1s, and obs_time is emitting a new long integer every 1s.
2. Consolidate data: To consolidate the data they send,
Student-Observable.timer (2,timeunit.seconds)
Time-Observable.interval (2, Timeunit.seconds)
Limited to a certain life cycle, the data emitted by obs_stu and the data emitted by Obs_time are matched with the returned observable.
3. Merging data: By FUNC2, define merge rule merge launch

The Join method uses the following:
Observablea.join (Observableb,
Observablea produces the result life cycle control function,
Observableb produces the result life cycle control function,
Observablea the results of the Observableb and the merging rules of the results produced by the
Parameter resolution:
* Observableb: A second observable combined with the source observable
* Observablea produces a result life cycle control function: The data emitted by the source observable and the data emitted from the second observable mate with the observable returned in the specified life cycle.
* Observableb produces a result life cycle control function: The data emitted by the second observable and the data emitted from the source observable in conjunction with the returned observable in the specified life cycle.
* Merge rule func: Defines how the emitted data is combined with the newly-emitted data item to merge and emit under the corresponding rules.
combinelatestThe combinelatest operator is a bit like a special form of the zip operator that will be used to transmit data recently. Look at the flowchart below, if Observable1 fired 2 and Observable2 fired A, B, C, D,combinelatest () will be grouped to handle 2a,2b, After 2 C and 2d.observable1 fired 3, combinelatest () will process 3D.

Combinelatest operator Flowchart:


Example code:
    observable<student> Obs_stu = observable.interval (1, timeunit.seconds)        . Map (Position-Mlists.get ( Position.intvalue ()));    observable<long> obs_time =            observable.interval (timeunit.milliseconds);    Observable.combinelatest (Obs_stu,            obs_time,            this::updatetitle)            . Observeon ( Androidschedulers.mainthread ())            . Subscribe (New observer<student> () {                @Override public                Void OnCompleted () {                }                @Override public                void OnError (Throwable e) {                }                @Override public                Void OnNext (Student Student) {                    madastu.adddata (Student);                }            });


And,then and whenThe And,then and when operators use the pattern and plan as mediations in the Rxjava joins package to merge the emitted datasets together. Need to guide package joins package, Androidstudio in Gradle reference: Compile ' io.reactivex:rxjava-joins:0.22.0 ', if this package is not referenced, class pattern, Plan and joinobservable do not exist.

The flowchart for the And,then and when operators is as follows:


Example code:
    observable<student> Obs_stu = Observable.from (mlists);    observable<long> obs_time = observable.interval (1, timeunit.seconds);    Pattern2<student, long> pattern = Joinobservable.from (Obs_stu). and (Obs_time);    Plan0<student> plan = Pattern.then (this::updatetitle);    Joinobservable            . When (plan)            . toobservable ()            . Observeon (Androidschedulers.mainthread ())            . Subscribe (new observer<student> () {                @Override public                void oncompleted () {                }                @Override Public                void OnError (Throwable e) {                }                @Override public                void OnNext (Student Student) {                    Madastu.adddata (student);                }            });


Look at the sample code and the and, then, and when processes are as follows:
1. Create the emitter Source: Obs_stu Emit student data, obs_time emit a long integer per second
2. Creating a Pattern Object
3. Using the Pattern object you just created, create a plan object, that is, what is the Observables,then () that we have two transmit data for? "
4. When the plan object exists, what should be done if plan occurs, that is. When (plan). Toobservable ()
5. The end is subscription

SwitchThe switch operator, as defined, converts a observable that emits multiple observables into a separate observable, which emits the data items that the observables recently launched.
A source Observable,switch () that emits multiple observables sequences is given a subscription to the source observable and then starts transmitting the same data emitted by the first observable emitted. When the source observable launches a new observable, switch () immediately cancels the observable of the previous transmit data (thus interrupting the stream from which it was emitted) and then subscribes to a new observable and starts transmitting its data.
The flowchart of the switch operator is as follows:

StartwithThe startwith operator first emits a data sequence by passing a parameter.
The flowchart for the Startwith operator is as follows:

Example code:
    Subscription sub = observable.interval (1, timeunit.seconds)        . Map (Position-mlists.get (Position.intvalue ()))        . Startwith (Mlists.get (2))        . Observeon (Androidschedulers.mainthread ())        . Subscribe (New observer<student> () {            @Override            public void oncompleted () {            }            @Override public            void OnError (Throwable e) {            }            @Override            public void OnNext (Student Student) {                madastu.adddata (Student);            }        });


As in the example code, call the. Startwith (Mlists.get (2)) function to prioritize the third data from the sequence. In fact, the data A13 priority is received by the Observer, which confirms this point.


Combination of rxjava-operators observable

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.