Rxjava Study (i)

Source: Internet
Author: User
Tags iterable

Note: text and pictures reproduced from the parabola blog

Reference: http://gank.io/post/560e15be2dca930e00da1083

What the hell is RxJava?

One word: async .

RxJava's self-introduction on the GitHub homepage is "A library for composing asynchronous and event-based programs using observable sequences for th e java VM "(a library that uses observable sequences on a Java VM to compose an asynchronous, event-based program). This is RxJava, which is a very precise generalization.

However, for beginners, this is too ugly to understand. Because it is a "summary", and beginners need an "introduction."

In fact, the essence of RxJava can be compressed into the word async. On the root, it is a library that implements asynchronous operations, and other attributes are based on this.

RxJava fortunately

In other words, "the same is done asynchronously, why do people use it instead of ready-made asynctask/handler/xxx/...?" 』

One word: concise .

The key point of asynchronous operations is the simplicity of the program, because asynchronous code is often difficult to write and readable when the scheduling process is complicated. Android created AsyncTask and Handler , in fact, is to make the asynchronous code more concise. The advantage of RxJava is simplicity, but its simplicity is unique in that it remains concise as the program logic becomes more complex.

RxJava's Observer pattern

RxJava has four basic concepts: Observable (observable, i.e. the observer), ( Observer observer), subscribe (subscription), event. Observableand Observer by subscribe() means of the subscription relationship, so that Observable you can issue events when needed to notify Observer .

Unlike the traditional observer pattern, the RxJava event callback method defines two special events, in addition to the normal event onNext() (equivalent onClick() / onEvent() ): onCompleted() and onError() .

    • onCompleted(): Event queue end. RxJava not only handles each event separately, but also considers them as a queue. RxJava requires that the onNext() triggering method be used as a flag when no new issues are issued onCompleted() .
    • onError(): Event Queue exception. When an exception occurs during the event processing, it onError() is triggered, the queue is automatically terminated, and no more events are allowed to be emitted.
    • In a correctly-run sequence of events, onCompleted() and onError() there is only one, and is the last in the sequence of events. It is important to note that the onCompleted() onError() two are also mutually exclusive, that is, one is called in the queue, and the other should not be called again.

RxJava's observer pattern is roughly as follows:

2. Basic implementation

Based on the above concepts, the basic implementation of RxJava has three main points:

1) Create Observer

Observer is the Observer, which determines what behavior will occur when the event is triggered.

In addition Observer to the interface, RxJava also has an implemented Observer abstract class: Subscriber . Subscriber Observer There are some extensions to the interface, but their basic usage is exactly the same:

Not only the basic use of the same way, in essence, in the RxJava subscribe process, the Observer   will always be converted to a   subscriber   Re-use. So if you only want to use the basic function, select   Observer   and   subscriber   is exactly the same. The difference between them is that there are two main points for the user:

    1. onStart(): This is an Subscriber added method. It can be used to do some preparatory work, such as clearing 0 or resetting the data, before the subscribe is started and the event has not been sent. This is an optional method, and by default its implementation is empty. It is important to note that if the line threads requirements for the preparation work (for example, a dialog box that shows progress, which must be performed on the main thread), it onStart() does not apply because it is always called on the thread that occurs in subscribe and cannot be specified by the thread. To prepare for the specified thread, you can use the doOnSubscribe() method, which you can see in the following article.
    2. unsubscribe(): This is the Subscriber method of another interface that is implemented Subscription to cancel the subscription. After this method is called, the Subscriber event is no longer received. Generally before this method is called, you can use the isUnsubscribed() first to determine the state. unsubscribe()This method is important because subscribe() after that, the Observable reference will be held, and Subscriber if this reference is not released in time, there will be a risk of memory leaks. So it's a good idea to keep a principle: to dismiss a reference relationship as soon as possible in a suitable place (such as in a method) when it is no longer in use onPause() onStop() unsubscribe() to avoid a memory leak.
2) Create Observable

Observable is the Observer, which determines when events are triggered and what events are triggered. RxJava uses create() the method to create a Observable and defines an event-triggering rule for it. As you can see, the parameter here passes an OnSubscribe object as a parameter. is OnSubscribe stored in the returned Observable object, it acts as a schedule, and when Observable subscribed, OnSubscribe the method is call() automatically called, and the sequence of events is triggered sequentially according to the setting (for the above code, the Observer Subscriber will be called three times. c8/> and one time onCompleted() ). Thus, by invoking the Observer's callback method by the observer, it implements the event passed by the observer to the observer, the Observer pattern.

create()The RxJava method is the most basic method of creating sequence of events. Based on this approach, RxJava also provides methods to quickly create event queues, such as:

    • just(T...): Sends the incoming parameters in turn.
    • from(T[])/ from(Iterable<? extends T>) : Sends the incoming array Iterable , or splits it into a specific object, in turn.
3) Subscribe (subscription)

After creating Observable and then Observer using subscribe() methods to connect them together, the whole chain can work.

One might notice that subscribe() this approach is a bit odd: it appears to be " observalbe subscribed observer subscriber to/" rather than " observer / subscriber subscribed observalbe ", which looks like the "magazine subscribes to the reader" and reverses the object relationship. This is a bit awkward to read, but if the API is designed to observer.subscribe(observable) / subscriber.subscribe(observable) , although more in line with the logic of thinking, but the design of the streaming API has an impact, compared with the obvious is not worth the candle.

Observable.subscribe(Subscriber)The internal implementation of this is this (core code only):

// Note: This is not the source code of the subscribe (), but the code in the source codes related to performance, compatibility, extensibility, after culling of the kernel.  //  If you need to see the source code, you can go to RxJava's GitHub warehouse to download.   Public Subscription Subscribe (subscriber subscriber) {    subscriber.onstart ();    Onsubscribe.call (subscriber);     return subscriber;}
As you can see, subscriber() 3 things have been done:
    1. Called Subscriber.onStart() . This method has been described earlier and is an optional preparation method.
    2. Called Observable in the OnSubscribe.call(Subscriber) . Here, the logic to send the event begins to run. It can also be seen that in RxJava, the Observable event is not immediately started when it is created, but when it is subscribed, when the subscribe() method executes.
    3. Returns the incoming Subscriber as Subscription . This is for convenience unsubscribe() .

The relationships between objects throughout the process are as follows:

Or you can look at the diagram:

Complete 3-Step code:

 Public Static voidLearnrxjava () {//Generate observerObserver<string> Observer =NewObserver<string>() {@Override Public voidoncompleted () {} @Override Public voidOnError (Throwable e) {} @Override Public voidOnNext (String s) {}}; //Generate subscriber//two more useful ways to OnStart and unsubscribe.subscriber<string> subscriber =NewSubscriber<string>() {@Override Public voidOnStart () {Super. OnStart (); } @Override Public voidoncompleted () {} @Override Public voidOnError (Throwable e) {} @Override Public voidonNext (String o) {}}; if(subscriber.isunsubscribed ()) {subscriber.unsubscribe (); }        //three ways to generate observable//1.createobservable<string> Observable = Observable.create (NewObservable.onsubscribe<string>() {@Override Public voidCall (SUBSCRIBER&LT;?SuperString>subscriber) {Subscriber.onnext ("1"); Subscriber.onnext ("2"); Subscriber.onnext ("3");            Subscriber.oncompleted ();        }        }); //2.just//will be called in turn://OnNext (1); //OnNext (2); //OnNext (3); //OnNext (4); //oncompleted ();observable<integer> observable1 = Observable.just (1, 2, 3, 4); //3.from parameter passed in a collection//will be called in turn://OnNext (1); //OnNext (2); //OnNext (3); //OnNext (4); //oncompleted ();integer[] Numbers =Newinteger[]{1,2,3,4}; Observable<Integer> Observable2 =Observable.from (numbers);
        OBSERVABLE.SUBSCRIBE (Observer);
}

In addition to subscribe(Observer) and and support for incomplete subscribe(Subscriber) subscribe() defined callbacks, RxJava is automatically created by definition Subscriber . The form is as follows:

Action1<string> onnextaction =NewAction1<string>() {    //OnNext ()@Override Public voidCall (String s) {LOG.D (tag, s); }}; Action1<Throwable> onerroraction =NewAction1<throwable>() {    //OnError ()@Override Public voidCall (Throwable throwable) {//Error Handling    }}; Action0 oncompletedaction=NewAction0 () {//oncompleted ()@Override Public voidCall () {LOG.D (tag,"Completed"); }};//create subscriber automatically, and use Onnextaction to define ONNEXT ()Observable.subscribe (onnextaction);//automatically create subscriber and use Onnextaction and onerroraction to define OnNext () and OnError ()Observable.subscribe (onnextaction, onerroraction);//automatically create subscriber and use Onnextaction, onerroraction, and oncompletedaction to define OnNext (), OnError (), and oncompleted ()Observable.subscribe (Onnextaction, onerroraction, oncompletedaction);

Simply explain what happens in this code.Action1AndAction0Action0is an interface of RxJava, it has only one methodcall(), this method has no parameter and no return value;onCompleted()The method also has no parameter and no return value, soAction0Can be treated as a wrapper object that willonCompleted()The content is packaged to pass in as a parameter.subscribe()To implement a callback that is not fully defined. This can actually be seen as aonCompleted()Method is passed as a parameter into thesubscribe(), which is equivalent to "closures" in some other languages.Action1is also an interface, it also has only one methodcall(T param), this method also has no return value, but has a parameter;Action0Similarly, becauseonNext(T obj)AndonError(Throwable error)is also a single parameter with no return value, soAction1can addonNext(obj)AndonError(error)Package up incomingsubscribe()To implement a callback that is not fully defined. In fact, althoughAction0AndAction1Most widely used in the API, but RxJava is provided with multipleActionXinterface of the form (for example,Action2,Action3), they can be used to wrap different methods without return values.

Note: As mentioned earlier, Observer and Subscriber have the same role, and Observer in the subscribe() process will eventually be converted to Subscriber objects, so from here, the following description I will use Subscriber to replace Observer , so more rigorous.

Rxjava Study (i)

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.