Rxjava (i: Basic article)

Source: Internet
Author: User

RxJavaareAndroidBecome more and more popular among developers. The only problem is that it's not easy to get started, especially when most people use imperative programming languages. But once you figure it out, you'll find Rxjava really great.

Here is just to help you understand Rxjava, the entire series A total of four articles, I hope you read these four articles can understand Rxjava behind the thought, and like Rxjava.

Basis

Rxjava's core two things are observables (Observer, event source) and Subscribers (Observer). Observables emits a series of events that subscribers handle these events. The event here can be anything you are interested in (touch event, the data returned by the Web interface call ...). )

A observable can issue 0 or more events, knowing the end or error. Each event is emitted, the OnNext method of its subscriber is called, and the Last Call Subscriber.onnext () or Subscriber.onerror () ends.


Rxjava seems to want to design the observer pattern in the pattern, but there is a clear difference, that is, if a observerble does not have any subscriber, then this observable will not emit any events.

Hello World Creating a observable object is simple, call observable.create directly
observable<string> myobservable = observable.create (    new observable.onsubscribe<string> () {        @ Override public        void Call (SUBSCRIBER<? Super String> Sub) {            sub.onnext ("Hello, world!");            Sub.oncompleted ();        }    });
The observable object defined here simply emits a Hello world string, and then it ends. We then create a subscriber to handle the strings emitted by the observable object.
subscriber<string> mysubscriber = new subscriber<string> () {    @Override public    void OnNext (String s ) {System.out.println (s);}    @Override public    void oncompleted () {}    @Override public    void OnError (Throwable e) {}};
Here subscriber just prints the string that observable sent. The Subscribe function allows you to associate our defined Myobservable object with the Mysubscriber object, which completes the subscriber subscription to observable.
Myobservable.subscribe (Mysubscriber);
Once Mysubscriber subscribes to myobservable,myobservable is called Mysubscriber object OnNext and OnComplete method, Mysubscriber will print out Hello world! Does the more concise code feel like it's too verbose to write so much code just to print a Hello world? I'm mainly here to show rxjava behind the principle of the use of this relatively verbose notation, Rxjava actually provides a lot of convenient functions to help us reduce the code.

Let's start by looking at how to simplify the creation of observable objects. Rxjava contains many functions that simplify the creation of observable objects, such as Observable.just, which is used to create a observable object that ends with just one event, and the code that creates the observable object can be simplified to a single line
observable<string> myobservable = Observable.just ("Hello, world!");
Next look at how to simplify the subscriber, in the above example, we do not really care about oncomplete and onerror, we only need to do some processing in onnext, this time we can use the Action1 class.
action1<string> onnextaction = new action1<string> () {    @Override public    void Call (String s) {        System.out.println (s);    }};
The Subscribe method has an overloaded version that accepts parameters of three Action1 types, respectively, corresponding to Onnext,oncomplete, onerror functions.
Myobservable.subscribe (Onnextaction, onerroraction, oncompleteaction);
Here we don't care about onerror and oncomplete, so we just need the first parameter to
Myobservable.subscribe (onnextaction);//Outputs "Hello, world!"
The code above can eventually be written like this
Observable.just ("Hello, world!")    . Subscribe (new action1<string> () {        @Override public        void Call (String s) {              System.out.println (s);        }    });
Use java8 lambda to make your code more concise
Observable.just ("Hello, world!")    . Subscribe (S-System.out.println);
In Android development, it is highly recommended to use the Retrolambda Gradle plugin so that you can use lambda in your code.
Transform let's do something more interesting!
For example, if I wanted to add my signature to Hello World, you might want to modify the observable object:
Observable.just ("Hello, world! -dan ")    . Subscribe (S-System.out.println (s));
This is certainly possible if you can change the observable object, but what if you can't modify the observable object? For example, are observable objects provided by third-party libraries? For example, my observable object is subscribed by multiple subscriber, but I just want to make a change to a subscriber?
So what about the changes to the event in subscriber? For example, the following code:
Observable.just ("Hello, world!")    . Subscribe (S-System.out.println (S + "-dan"));
This is still not satisfying because I want my subscribers to be as lightweight as possible because I might run subscriber in Mainthread. In addition, according to the concept of reactive function programming, the subscribers should do is "respond", respond to events emitted by observable, rather than modify it. If I can be in some intermediate steps to "Hello world! "Isn't it cool to do transformations?"
The Operators operator is intended to solve the problem of transformations on observable objects, which are used to modify observable-emitted events between observable and the final subscriber. Rxjava provides a number of useful operators.
For example, the map operator is used to convert an event to another event.
Observable.just ("Hello, world!")  . Map (new func1<string, string> () {      @Override public      String Call (string s) {          return s + "-dan";      }  })  . Subscribe (S-System.out.println);
Using lambda can be simplified to
Observable.just ("Hello, world!")    . Map (S-S + "-dan")    . Subscribe (S-a System.out.println (s));
Isn't it cool? The map () operator is used to transform the observable object, and the map operator returns a observable object so that chained calls can be made and the map operator is used multiple times on a observable object. Finally, the most concise data is passed to the Subscriber object. The more interesting point of the map operation Fu Jinjie The map operator is that it does not have to return the type returned by the observable object, and you can use the map operator to return a observable object that emits a new data type.
For example above, subscriber does not care about the returned string, but rather the hash value of the string.
Observable.just ("Hello, world!")    . Map (new func1<string, integer> () {        @Override public        Integer Call (String s) {            return S.hashcode ();        }    })    . Subscribe (i-System.out.println (integer.tostring (i)));
It's funny, isn't it? Our initial observable returned a string, and the final subscriber received an integer, which, of course, would further simplify the code by using lambda:
Observable.just ("Hello, world!")    . Map (S-s.hashcode ())    . Subscribe (i-System.out.println (integer.tostring (i)));
As I said earlier, the fewer things subscriber do, the better we add a map operator
Observable.just ("Hello, world!")    . Map (S-s.hashcode ())    . Map (integer.tostring (i)) subscribe (S-a    System.out.println (s));
Refuses Do you think our example is too simple to convince you? You need to understand the following two points:

1.Observable and subscriber can do anything
Observable can be a database query, Subscriber used to display the results of the query, observable can be a screen click event, subscriber to respond to the click event; observable can be a network request, The Subscriber is used to display the request results.

2.Observable and Subscriber are independent of the intermediate transformation process.
You can increase or decrease any number of maps in the middle of observable and subscriber. The entire system is highly composable, and manipulating the data is a very simple process.

      • Previous Android log you do not know the tips
      • The next step to get started with Otto

Rxjava (i: Basic article)

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.