Simple Rxjava (one: Basic) __java

Source: Internet
Author: User
Tags emit

Original link

Rxjava is becoming increasingly popular with Android developers. The only problem is that it's not easy to get started, especially when most people use an imperative programming language. But once you figure it out, you'll find Rxjava really great.
Here is just to help you understand Rxjava, the whole series has four articles, I hope you read these four articles can understand Rxjava behind the thought, and like Rxjava.
Base

The two core Rxjava are observables (observed, event source) and Subscribers (Observer). Observables emits a series of events subscribers handle these events. The event here can be anything you are interested in (touch events, web interface calls return data ...). )

A observable can emit 0 or more events, knowing the end or error. Each event is emitted, its subscriber OnNext method is invoked, and the last Call to Subscriber.onnext () or Subscriber.onerror () ends.


Rxjava looks like the observer pattern in the design pattern, but there is one obvious difference, that is, if a observerble does not have any subscriber, then this observable does not emit any events.
Hello World to create a observable object is very simple, directly call Observable.create can

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 string 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 print the observable out of the string. By using the Subscribe function, we can associate the Myobservable object we defined with the Mysubscriber object, thus completing the Subscriber subscription to observable.
Myobservable.subscribe (Mysubscriber);
Once Mysubscriber subscribe to myobservable,myobservable is the OnNext and OnComplete method of calling Mysubscriber objects, Mysubscriber prints out Hello world. More Concise CodeDo you think it's too verbose to write so much code just to print a Hello world? I am here mainly to show the principle behind the Rxjava and use this more verbose writing, Rxjava actually provides a lot of convenient functions to help us reduce the code.

First let's look at how to simplify the creation of observable objects. Rxjava has a number of built-in functions for simplifying the creation of observable objects, such as Observable.just, which is used to create observable objects that simply emit an event, and the code that creates the observable object can be simplified to one line
observable<string> myobservable = Observable.just ("Hello, world!");
Let's take a look at how to simplify subscriber, in the example above, we don't really care about oncomplete and onerror, we just need to do some processing when onnext, and then 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 three Action1 types of arguments, corresponding to the Onnext,oncomplete, onerror functions.
Myobservable.subscribe (Onnextaction, onerroraction, oncompleteaction);
We don't care about onerror and oncomplete here, so we just need the first argument 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);
        }
    });
Using Java8 's lambda can make your code simpler
Observable.just ("Hello, world!")
    . Subscribe (s-> System.out.println (s));
In Android development, it's highly recommended to use the Retrolambda Gradle plugin so you can use lambda in your code.
TransformLet's do something more interesting.
For example, I want to add my signature to Hello World, you might think of modifying the observable object:
Observable.just ("Hello, world! -dan ")
    . Subscribe (S-> System.out.println (s));
If you can change the observable object, this is certainly OK, but if you can't modify the observable object. For example, the observable object is provided by a Third-party library. For example, my observable object is subscribed to by multiple subscriber, but I just want to make a change to a subscriber.
So what about changing events in the 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 light as possible because I have the possibility to run subscriber in Mainthread. In addition, according to the concept of response function programming, subscribers should do is "response", in response to the events emitted by observable, rather than to modify it. If I can in some intermediate step to "Hello world." "It's cool to make a transformation."
operator (Operators)operator is to solve the problem of the transformation of the observable object, the operator is used to modify the observable event between the observable and the final subscriber. Rxjava provides many useful operators.
The map operator, for example, is used to convert an event to another event.
Observable.just ("Hello, world!")
  . Map (new func1<string, string> () {
      @Override public
      string called (string s) {return
          s + "-dan";
      }
  })
  . Subscribe (s-> System.out.println (s));
Using a lambda can be simplified to
Observable.just ("Hello, world!")
    . Map (s-> s + "-dan")
    . Subscribe (S-> 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 a chained invocation can be implemented that uses the map operator multiple times on a observable object. Finally, the most concise data is passed to the Subscriber object. map Operations Fu JinjieThe more interesting point of 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, in the above example, subscriber doesn't care about the returned string, but 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. Our initial observable returns a string, and the final subscriber receives an integer, of course, using a lambda can further simplify the code:
Observable.just ("Hello, world!")
    . Map (S-> s.hashcode ())
    . Subscribe (i-> System.out.println (integer.tostring (i)));
As I said before, the fewer things subscriber do, the better, we add a map operator
Observable.just ("Hello, world!")
    . Map (S-> s.hashcode ())
    . Map (i-> integer.tostring (i))
    . Subscribe (S-> System.out.println (s));
Defy. 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 query results, observable can be on-screen click events, subscriber to respond to click events, observable can be a network request, Subscriber is used to display the request results.

2.Observable and Subscriber are independent of the intermediate transformation process.
Any number of maps can be added or subtracted between observable and subscriber. The whole system is highly configurable, and manipulating the data is a very simple process.


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.