Rxjava's Development Learning notes

Source: Internet
Author: User
Tags iterable throwable

Recently looking at the Android framework, see retrofit this network request, see Retrofit and see Rxjava, have been heard Rxjava, this time I decided to start learning Rxjava. Read some blogs and recommend the following two great God blogs http://gank.io/post/560e15be2dca930e00da1083 and http://blog.csdn.net/lzyzsd/article/details/ 41833541, this article is also in the above two blog based on their own summary. First put the GitHub link and introduce the dependent Gradle code, https://github.com/ReactiveX/RxJava,https://github.com/ReactiveX/RxAndroid;
Introducing Dependencies:

Compile ' io.reactivex:rxandroid:1.2.1 '
Compile ' io.reactivex:rxjava:1.1.6 '

What the hell is Rxjava?

One word: Asynchronous.

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

In fact, the essence of Rxjava can be compressed into the word asynchronous. Speaking of Roots, it is a library that implements asynchronous operations, and other attributes are based on this.

Where's Rxjava?

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

A word: simplicity.

The key point of asynchronous operation is the simplicity of the program, because the asynchronous code is often difficult to write and read when the scheduling process is more complex. The Asynctask and handler created by Android are all meant to make asynchronous code simpler. Rxjava's advantage is simplicity, but its simplicity is unique in that it can remain concise as the logic of the program becomes more complex.

Concept: An extended observer model

Rxjava has four basic concepts: observable (observable, i.e. observed), OBSERVER (Observer), subscribe (subscription), event. Observable and observer implement subscription relationships through the Subscribe () method, which observable can emit events when needed to pass observer.

Unlike traditional observer patterns, the Rxjava event callback method defines two special events in addition to the normal event OnNext () (the equivalent of OnClick ()/OnEvent ()): OnCompleted () and OnError ().

OnCompleted (): End of event queue. Rxjava not only handles each event individually, it also sees them as a queue. Rxjava stipulates that when no new OnNext () is issued, the oncompleted () method must be triggered as a flag.
OnError (): Event queue exception. When an exception occurs during event handling, the OnError () is triggered, and the queue is terminated automatically, allowing no further events to be issued.
In a correctly running sequence of events, oncompleted () and OnError () have only one, and are the last in the sequence of events. It should be noted that oncompleted () and OnError () are mutually exclusive, that is, one of them is invoked in the queue, and no more calls should be made to the other.

Basic implementation

1) Create Observer/subscriber
2) Create observable
3) Subscribe (subscribe)

Below I put all of the integration in an activity, layout file put a imageview, do not paste code;

public class Mainactivity extends Appcompatactivity {
Private ImageView ImageView;
int drawableres = r.mipmap.icon_yao_my;

@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
ImageView = (ImageView) Findviewbyid (R.id.imageview);
1) Create Observer/subscriber
observer<string> Observer = new observer<string> () {//CREATE Observer Observer
@Override
public void oncompleted () {//Event queue end

}

@Override
public void OnError (Throwable e) {//Event queue exception

}

@Override
public void OnNext (String s) {//Normal event
LOG.V ("mainactivity===", s);
}
};

subscriber<string> subscriber = new subscriber<string> () {//Create subscription
@Override
public void oncompleted () {

}

@Override
public void OnError (Throwable e) {

}

@Override
public void OnNext (String s) {
LOG.V ("mainactivity===", s);
}

@Override
public void OnStart () {
Super.onstart ();
}
};

The basic use of Observer and Subscriber is exactly the same, in essence, in the Rxjava subscribe process, Observer will always be converted into a
Subscriber to use again. So if you just want to use basic functionality, choosing Observer and Subscriber is exactly the same.
The difference between them is mainly two points for the user:
1. OnStart (): This is the method of subscriber increase. It will be called at the beginning of subscribe, and the event has not been sent before it can be used to do some preparatory work, such as clearing 0 or resetting the data.
This is an optional method, and its implementation is empty by default. It is important to note that if the line Chengyu required for the preparation (for example, a dialog box that displays progress is displayed, this must be done in the main thread),
OnStart () does not apply because it is always invoked on a thread that occurs in subscribe and cannot specify a thread. To prepare for a specified thread, you can use the Doonsubscribe () method,
Can be seen in the following text.
2. Unsubscribe (): This is another method implemented by subscriber that Subscription to unsubscribe.
After this method is invoked, Subscriber will no longer receive events. In general, before this method is called, you can use isunsubscribed () to judge the state first.
Unsubscribe () This method is important because after subscribe (), observable will hold a reference to subscriber, which, if not released in time,
There will be a risk of memory leaks.
So it's a good idea to keep the principle of calling unsubscribe () as soon as possible in the right place (such as OnPause () OnStop (), and so on) when no longer in use,
To prevent memory leaks from occurring.
//

2) Create observable
Observable observable = Observable.create (new observable.onsubscribe<string> () {

@Override
public void Call (SUBSCRIBER&LT. Super string> Subscriber) {
Subscriber.onnext ("Hello");
Subscriber.onnext ("Hi");
Subscriber.onnext ("Aloha");
Subscriber.oncompleted ();
}
});

3) Subscribe (subscribe)
OBSERVABLE.SUBSCRIBE (Observer);
Or:
Observable.subscribe (subscriber);

Note: the Create () method is the most basic method of creating event sequences Rxjava. Based on this approach, Rxjava also provides a number of ways to quickly create event queues, such as:

Just (T ...): Send incoming arguments in sequence.
Observable observable1 = Observable.just ("Hello", "Hi", "Aloha");

From (t[])/from (ITERABLE&LT;? extends T>): After splitting the passed-in array or iterable into concrete objects, send them sequentially.
string[] Words = {"Hello", "Hi", "Aloha"};
Observable observable2 = Observable.from (words);

Example: A. Print an array of strings

Observable.from (words). Subscribe (New action1<string> () {//Action1 is an interface, it has only one method call (T param), and this method has no return value, But there is a parameter;
@Override
public void Call (String s) {
LOG.V ("mainactivity===", s);
}
});
B. Get pictures from ID and show
Observable.create (New observable.onsubscribe<drawable> () {
@Override
public void Call (SUBSCRIBER&LT. Super drawable> Subscriber) {
drawable drawable = Getresources (). getdrawable (Drawableres);
Subscriber.onnext (drawable);
Subscriber.oncompleted ();

}
}). Subscribe (New observer<drawable> () {
@Override
public void oncompleted () {

}

@Override
public void OnError (Throwable e) {
Toast.maketext (Mainactivity.this, "error!", Toast.length_short). Show ();
}

@Override
public void OnNext (drawable drawable) {
Imageview.setimagedrawable (drawable);
}
});
}

}
The above implementation is just a synchronized observer pattern. The object of the observer pattern itself is the asynchronous mechanism of "background processing, foreground callback," so Asynchrony is critical to Rxjava. To implement Asynchrony, you need to use another concept of Rxjava: Scheduler. Next issue;

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.