The simplest and easiest to understand the basic use of the RxJava2 of the RxJava2.0 Learning Tutorial (i) __rxjava2

Source: Internet
Author: User
Tags emit throwable

Last year RxJava2 released, after this has been doing projects are in use RXJAVA2, feel particularly useful, the current online information a lot, for the previous use of RXJAVA1 friends only need to see the updated document to know how to use, But there are some former Rxjava friends may not know how to do, do not know whether to see RXJAVA1 or direct learning RxJava2. If you have studied RxJava1 before, then for the RXJAVA2 only need to see what the updated things on the line, RxJava2 relative to RxJava1 the core of the idea has not changed, if you have not learned RxJava1, no relationship, direct learning RxJava2. So here to share with friends RxJava2 knowledge, hope to help everyone. First, the configuration

To use RXJAVA2 in Android, add dependencies to the app's Build.gradle:

Compile ' io.reactivex.rxjava2:rxjava:2.x.y '
compile ' io.reactivex.rxjava2:rxandroid:2.0.1 '

One is the Rxjava library, the other is the Rxjava based on the Android library. Second, the principle

Below is the principle of Rxjava. There are many blogs about Rxjava principles on the web, and general articles start with the Observer model, the Observer, the Observer, the subscription relationship, and so on. When I first saw these articles, I was completely bewildered, I needed to see the observer pattern first, and then I understood Rxjava on the basis of the observer pattern. In short, it takes a long time to figure out the relationship between them.

I think it's easier to understand: with a river upstream and downstream instead of the observed and the observer, there is a sluice between upstream and downstream, the sluice is open when the connection is made, and the event can be received downstream each time an event is sent. The use of Rxjava is a three-step first step: Creating the observed

Create upstream observable (observed)
        observable<integer> observable = observable.create (new observableonsubscribe< Integer> () {
            @Override public
            void Subscribe (observableemitter<integer> emitter) throws Exception {
                Emitter.onnext (1);
                Emitter.onnext (2);
                Emitter.onnext (3);
                Emitter.oncomplete ();
            }
        );
Step Two: Create the viewer
Create downstream OBSERVER (Observer)
        observer<integer> Observer = new observer<integer> () {
            @Override public
            void Onsubscribe (disposable d) {
                log.d (TAG, "Onsubscribe");
            }

            @Override public
            void OnNext (Integer value) {
                log.d (TAG, "onnext=" + value);
            }

            @Override public
            void OnError (Throwable e) {
                log.d (TAG, "OnError");
            }

            @Override public
            void OnComplete () {
                log.d (TAG, "OnComplete");
            }
        ;
Step Three: Establish a subscription relationship
        Establish a connection
        OBSERVABLE.SUBSCRIBE (Observer);

Run Result:

The order in which events are sent here is 1,2,3, and the order in which the events are received is also in the order of 1,2,3. The
upstream and downstream correspond to the observable and observer in the Rxjava respectively, and the connection between them corresponds to the subscribe (). The
only upstream observable and (downstream) observer have established a connection before sending the event. That is, the subscribe () method is invoked before the event is sent.
Linking this code to writing became known as the Rxjava chain operation, and the result is the same:

 Observable.create (new observableonsubscribe<integer> () {@Override
                public void Subscribe (observableemitter<integer> emitter) throws Exception {Emitter.onnext (1);
                Emitter.onnext (2);
                Emitter.onnext (3);
            Emitter.oncomplete (); . Subscribe (New observer<integer> () {@Override public void Onsubscribe (DISPOSABL
            E d) {log.d (TAG, "onsubscribe");
            @Override public void OnNext (Integer value) {LOG.D (TAG, "onnext=" + value);
            @Override public void OnError (Throwable e) {log.d (TAG, "onError");
            @Override public void OnComplete () {LOG.D (TAG, "OnComplete"); }
        });

Explain two keywords: observableemitter and disposable observableemitter:

Emitter is the transmitter, this is used to emit the event, it can emit three kinds of events, by calling emitter OnNext (T value), OnComplete () and onerror (throwable error) You can emit the next event, the complete event, and the error event separately.
Here's what you need to be aware of:
1, upstream can send unlimited onnext, downstream can also receive unlimited onnext. When a oncomplete is sent upstream, the events after the upstream OnComplete will continue to be sent, and the downstream receive the OnComplete event will no longer continue to receive events.
2. When a onerror is sent upstream, the events after the upstream onerror will continue to be sent, and the downstream receive the OnError event will no longer continue to receive events. Upstream can not send oncomplete or onerror.
3, send multiple oncomplete can be normal operation, but received the first OnComplete no longer received, but if you send multiple onerror, you receive a second onerror event will cause the program will crash.

Let's try it all: 1, send multiple OnComplete

Observable.create (New observableonsubscribe<integer> () {@Override public void subscribe (Obs
                Ervableemitter<integer> emitter) throws Exception {log.d (TAG, "emitter=1");
                Emitter.onnext (1);
                LOG.D (TAG, "emitter=2");
                Emitter.onnext (2);
                LOG.D (TAG, "emitter=3");
                Emitter.onnext (3);
                LOG.D (TAG, "emitter=complete=1");
                Emitter.oncomplete ();
                LOG.D (TAG, "emitter=complete=2");
                Emitter.oncomplete ();
                LOG.D (TAG, "emitter=complete=3");
                Emitter.oncomplete ();
                LOG.D (TAG, "emitter=4");
            Emitter.onnext (4); . Subscribe (New observer<integer> () {@Override public void Onsubscribe (Disposab
            Le D) {log.d (TAG, "onsubscribe"); } @Override public void OnNext(Integer value)
            {LOG.D (TAG, "OnNext:" + value);
            @Override public void OnError (Throwable e) {log.d (TAG, "onError");
            @Override public void OnComplete () {LOG.D (TAG, "OnComplete"); }
        });

Run Result:

You can see that sending multiple oncomplete is OK, just receive a oncomplete after the event is not received, but the upstream is still sending events. 2. Send multiple OnError events

Observable.create (New observableonsubscribe<integer> () {@Override public void subscribe (Obs
                Ervableemitter<integer> emitter) throws Exception {log.d (TAG, "emitter=1");
                Emitter.onnext (1);
                LOG.D (TAG, "emitter=2");
                Emitter.onnext (2);
                LOG.D (TAG, "emitter=3");
Emitter.onnext (3);
LOG.D (TAG, "emitter=complete=1");
Emitter.oncomplete ();
LOG.D (TAG, "emitter=complete=2");
Emitter.oncomplete ();
LOG.D (TAG, "emitter=complete=3");
                Emitter.oncomplete ();
                LOG.D (TAG, "emitter=error=1");
                Emitter.onerror (New Throwable ("no Message"));
                LOG.D (TAG, "emitter=error=2");
                Emitter.onerror (New Throwable ("no Message"));
                LOG.D (TAG, "emitter=error=3"); Emitter.onerror (New Throwable ("No MEssage "));
                LOG.D (TAG, "emitter=4");
            Emitter.onnext (4); . Subscribe (New observer<integer> () {@Override public void Onsubscribe (Disposab
            Le D) {log.d (TAG, "onsubscribe");
            @Override public void OnNext (Integer value) {LOG.D (TAG, "OnNext:" + value); @Override public void OnError (Throwable e) {log.d (TAG, "onerror=" +
            E.getmessage ());
            @Override public void OnComplete () {LOG.D (TAG, "OnComplete"); }
        });

Run Result:

As you can see from this result, when the first onerror () is received, the error information is printed but the program does not crash, and the second onerror () program crashes. Disposable:

The meaning of the word: it is disposable and discarded after use. So how to understand it in Rxjava, corresponding to the example above, we can interpret it as a sluice, when the Dispose () method is called, the sluice is closed and the downstream is not receiving the event.
However, calling Dispose () does not allow the upstream to stop sending events, and instead continues to send the remaining events upstream.

Send 1,2,3,complete,4 upstream, after receiving the second event, close the sluice and look at the results of the operation:

Observable.create (New observableonsubscribe<integer> () {@Override public void subscribe (Obs
                Ervableemitter<integer> emitter) throws Exception {log.d (TAG, "emitter=1");
                Emitter.onnext (1);
                LOG.D (TAG, "emitter=2");
                Emitter.onnext (2);
                LOG.D (TAG, "emitter=3");
                Emitter.onnext (3);
                LOG.D (TAG, "emitter=complete");
                Emitter.oncomplete ();
                LOG.D (TAG, "emitter=4");
            Emitter.onnext (4);
            }). Subscribe (New observer<integer> () {Private disposable disposable;

            private int i;
                @Override public void Onsubscribe (disposable d) {log.d (TAG, "onsubscribe");
            disposable = D;
          @Override public void OnNext (Integer value) {LOG.D (TAG, "OnNext:" + value);      i++;
                    if (i = = 2) {disposable.dispose ();
                LOG.D (TAG, "isdisposed:" + disposable.isdisposed ()); @Override public void OnError (Throwable e) {log.d (TAG, "OnError"
            );
            @Override public void OnComplete () {LOG.D (TAG, "OnComplete"); }
        });

The results of the operation are:

From the operating results we saw that after receiving the OnNext (2) This event, the sluice was closed, but the upstream still sent OnNext (3), Complete, OnNext (4), and the upstream did not stop because the oncomplete was sent. You can also see that the downstream Onsubscribe () method is called first.
In addition, subscribe () has several overloaded methods:

    Public final Disposable Subscribe () {} public
    final disposable subscribe (CONSUMER<? Super T> OnNext) {}
    Pub  LIC final disposable subscribe (CONSUMER<? super t> OnNext, consumer< Super throwable> onError) {} public
    Final disposable Subscribe (consumer< Super t> OnNext, consumer< Super throwable> OnError, Action oncomplete {} public
    final disposable subscribe (consumer< Super t> onnext, consumer<? Super Throwable> OnError, Ac tion OnComplete, consumer<? Super Disposable> Onsubscribe) {} public
    final void subscribe (observer<. Super t> Observer) {}

The first subscribe () without any parameters indicates that the downstream does not care about what is being sent upstream.
The second method with a consumer parameter indicates that the downstream only cares about onnext events, and other events are not concerned, so if we only need OnNext events to write this, the code is as follows:

Observable.create (New observableonsubscribe<integer> () {
            @Override public
            void Subscribe ( Observableemitter<integer> emitter) throws Exception {
                log.d (TAG, "emitter=1");
                Emitter.onnext (1);
                LOG.D (TAG, "emitter=2");
                Emitter.onnext (2);
                LOG.D (TAG, "emitter=3");
                Emitter.onnext (3);
                LOG.D (TAG, "Emitter=complete");
                Emitter.oncomplete ();
                LOG.D (TAG, "emitter=4");
                Emitter.onnext (4);
            }
        }). Subscribe (new consumer<integer> () {
            @Override public
            void Accept (Integer integer) throws Exception { C16/>LOG.D (TAG, "Accept:" + integer);
            }
        );

The results of the operation are as follows:

The next few methods and the use of the second is the same, do not say more, the last method, in front of the article is used, also do not introduce.

Click to download Demo

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.