[Android] Brief introduction and basic use of Rxjava (i.) __java

Source: Internet
Author: User
Tags throwable

Preface

Rxjava and Rxandroid (https://github.com/ReactiveX/RxAndroid) have been burning for a while, and here is a brief introduction to them. 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). In fact, it has become a responsive Third-party library designed for Android, primarily because it is the first responsive Third-party library that can be used in all directions for Java support. Rxjava 2 retains all of the Java versions that we need to support on Android. Keywords: responsive programming , asynchronous

It boils down to three main components:

1. A set of classes used to represent a data source
2. A set of classes for listening to a data source
3. A set of methods for modifying and merging data
When you start listening to a data source, it starts or stops doing some action. You can think of it as a network request, unless you start listening to the network response, otherwise this network request will never be triggered. And if you cancel a subscription to the data source before the data source task completes, it is likely that the network request will be canceled.

These operations can be synchronous or asynchronous, so you can construct a network-like request that runs within a block of code, but runs on top of a background thread. Alternatively, it can be completely asynchronous, as if we were to eject an activity on Android or click on a component in the UI, which can be considered an asynchronous operation.

Typically, a network request produces only one response, but as long as your UI still exists there, even if you subscribe to only one button, you will find that the button's Click event flow may be infinite. In addition, the responses they generate may also be empty, so this type of data source actually has only two functions: success or failure, which does not generate any data. You can treat it like writing to a database or writing to a file. It does not actually return the relevant response or data; it either completes successfully or fails. This complete, failed response is built by Rxjava data sources, combined with so-called "terminal events" (Terminal event). This is similar to the way that you can return normally, or throw an exception.

This response is also likely to never end. Let's go back to the previous button click Action Example, and if we build the button click event as a data source, the response will never end as long as your UI still exists. It may not end until the UI disappears and you cancel the subscription to the button's Click event. Before that, it will never enter the state of completion.

All this is equivalent to achieving the traditional observer model. We have some components that can produce data, and then we just want to know what data they produce, so all we have to do is just observe. So we can add a listener, when the event occurs, we receive the corresponding notification.


Basic Use

There was a lot of chatter in front of me and it felt like there was no egg. Go straight to the point, for the program ape, the code is easier to understand than the text.

In Build.gradle, please rely on,

Compile ' io.reactivex.rxjava2:rxandroid:2.0.1 '
//Because Rxandroid releases are few and far, it is between D also
//explicitly depend on Rxjava ' s latest version for bug fixes and new features.
Compile ' io.reactivex.rxjava2:rxjava:2.0.1 '
private void createflowable (Final String str) {flowable<string> flowable = flowable.create (New Flowableonsu Bscribe<string> () {@Override public void subscribe (flowableemitter<string> e) throws
                Exception {//onnext method is to launch a task: For example, in this example, the Light Action E.onnext (str);
            Call E.oncomplete after the event is completed (); }}, Backpressurestrategy.buffer);
            Support back pressure, do not discard data processing mode subscriber<string> subscriber = new subscriber<string> () {@Override
                public void Onsubscribe (Subscription s) {log.d (TAG, "---onsubscribe---");
            The number of times that can be requested must be set, otherwise the OnNext and OnComplete method S.request (Long.max_value) will not be executed;
                @Override public void OnNext (String s) {log.d (TAG, "---onnext-->" + s);

            Toast.maketext (Mcontext, S, Toast.length_short). Show (); }

            @Override public void OnError (Throwable t) {log.e (TAG, "---onerror-->", t); @Override public void OnComplete () {LOG.D (TAG, "---oncomplete-->the light i
            s on ");
        }
        };
    Subscribe: Launch Source executes this event flowable.subscribe (subscriber); }
Createflowable ("Turn the Light on!"); Perform
04-20 13:43:08.904 12293-12293/org.jan.rxandroiddemo d/simplefunc1activity:---onsubscribe---
04-20 13:43:08.904 12293-12293/org.jan.rxandroiddemo d/simplefunc1activity:---onnext-->turn the light on!
04-20 13:43:08.944 12293-12293/org.jan.rxandroiddemo d/simplefunc1activity:---oncomplete-->the light is on
Flowable the effect is fluid, we can think of it as the source of some sort of event queue. To create a flowable emitter, suppose the program apes work overtime to turn on the lights. For one thing, turn on the lights and light up, and the action combination of the lights will be performed by flowable (subscribe). Subscriber can be imagined as an event handler and response receiver. After the light action, such as the physical reaction of the current through the bulb, is handled in the method (OnNext) of the object.








Do you think the writing is a bit complicated, rxjava, there is a just method, will automatically according to your input parameters of the call OnNext method OH

A wave of code to signal

  private void Createsimpleflowable (String params) {
        flowable.just (params). Subscribe (New consumer<string> () {
            @Override public
            Void Accept (String s) throws Exception {
                log.i (TAG, "---accept-->" +s);
                Toast.maketext (Mcontext, S, Toast.length_short). Show ();}}
    
Call Createsimpleflowable ("Turn the Light off!");
04-20 14:15:37.864 18583-18583/org.jan.rxandroiddemo i/simplefunc1activity:---accept-->turn the light off!


Getting Started with transformations

hahaha, we can also in the process of input to the output of the data to do the transformation operation, what meaning. On the code.

      Flowable.just ("hello! RxJava2 ")
                . Subscribe (New consumer<string> () {
                    @Override public
                    Void Accept (String s) throws Exception {
                        log.i (TAG, "Android-jan:" +s);
                    }
                );
04-20 14:37:07.634 15173-15173/org.jan.rxandroiddemo i/simplefunc1activity:android-jan:hello! RxJava2

operator

1.map conversion, the map function returns a converted Flowable object.

private void Map (String str) {
        flowable.just (str). Map (new function<string, string> () {
            @Override
            Public String apply (String s) throws Exception {
                //Here we do a little trick return
                s+ "3 o'clock in the afternoon";
            }
        ). Subscribe (new consumer<string> () {
            @Override public
            Void Accept (String s) throws Exception {
                log.i ( TAG, "---accept-->" +s);
                Toast.maketext (Mcontext, S, Toast.length_short). Show ();}}
    

Call my method: Map ("April 20, 2017"); Look at what's printed. In fact, you have a good result in mind.

04-20 15:44:48.834 25851-25851/org.jan.rxandroiddemo i/simplefunc1activity:---accept-->2017 year April 20 3 o'clock in the afternoon

Another wave to see if you can execute the double map,

/**
     * Converts the input parameter str hashcode to a String and prints it out
     * @param
     str
    /private void Map2 (String str) {
        Flowable.just (str). Map (new function<string, integer> () {
            @Override public
            Integer apply (String s) Throws Exception {return
                s.hashcode ();
            }
        }). Map (new Function<integer, string> () {
            @Override public
            String apply (Integer integer) throws Exception { return
                integer.tostring ();
            }
        }). Subscribe (new consumer<string> () {
            @Override public
            Void Accept (String s) throws Exception {
                LOG.I (tag,s);
                Toast.maketext (Mcontext, S, Toast.length_short). Show ();}}
    
Yes, the print results are correct.

2.fromIterable method, if I have a list in my hand now, I'm going to shoot it through flowable, and I'll teach you.

   list<integer> list = new arraylist<> ();
        List.add (ten);
        List.add ();
        List.add (a);
        List.add (256);
        List.add (1000);
        Flowable.fromiterable (list). Subscribe (New consumer<integer> () {
            @Override public
            void Accept (Integer Integer) throws Exception {
                log.i (TAG, "---from->" +integer);
            }
        );

Print results:

04-20 16:38:16.404 24914-24914/org.jan.rxandroiddemo i/simplefunc1activity:---from->10
04-20 16:38:16.404 24914-24914/org.jan.rxandroiddemo i/simplefunc1activity:---from->15
04-20 16:38:16.404 24914-24914/ Org.jan.rxandroiddemo i/simplefunc1activity:---from->20
04-20 16:38:16.404 24914-24914/ Org.jan.rxandroiddemo i/simplefunc1activity:---from->256
04-20 16:38:16.404 24914-24914/ Org.jan.rxandroiddemo i/simplefunc1activity:---from->1000

The 3.FLATMAP operator, which feels like a map, is actually more powerful than map, and is used to break nested structures. The first thing we can be sure of is that it can convert a flowable into another flowable.

  list<integer> list = new arraylist<> ();
        List.add (10);
        List.add (15);
        List.add (20);
        List.add (256);

        List.add (1000);
            Flowable.just (list). Flatmap (new Function<list<integer>, publisher<string>> () {@Override Public publisher<string> apply (list<integer> integers) throws Exception {//This code means nothing.
                , importantly, it can help you convert your input parameters and return a publisher emitter Source: flowable list<string> STRs = new arraylist<string> ();
                For (integer integer:integers) {strs.add (string.valueof (integer));
            Return flowable.fromiterable (STRs);  The. Subscribe (new defaultsubscriber<string> () {@Override public void OnNext (String
            s) {//Here is not an integer type, has been processed into string type LOG.I (TAG, "---onnext-->" +s); } @Override PUBlic void OnError (Throwable t) {log.e (TAG, "---onerror-->", t);
            @Override public void OnComplete () {log.i (TAG,---oncomplete---); }
        });
Print results:

04-20 17:28:39.044 3101-3101/org.jan.rxandroiddemo i/simplefunc1activity:---onnext-->10
04-20 17:28:39.044 3101-3101/org.jan.rxandroiddemo i/simplefunc1activity:---onnext-->15
04-20 17:28:39.044 3101-3101/ Org.jan.rxandroiddemo i/simplefunc1activity:---onnext-->20
04-20 17:28:39.044 3101-3101/ Org.jan.rxandroiddemo i/simplefunc1activity:---onnext-->256
04-20 17:28:39.044 3101-3101/ Org.jan.rxandroiddemo i/simplefunc1activity:---onnext-->1000
04-20 17:28:39.044 3101-3101/ Org.jan.rxandroiddemo i/simplefunc1activity:---oncomplete---
If you do not fully understand, please refer to the From () and Flatmap () method of Rxjava

4.filter operator, filter meaning, let's say we're going to filter a set of arrays.

  Integer[] array = {1,2,3,5,6,4,0};
        Flowable.fromarray (Array). Filter (new predicate<integer> () {
            @Override public
            boolean test (Integer Integer) throws Exception {
                //filter out the elements greater than 4 in the array return
                integer.intvalue () >4;
            }
        }). Subscribe (new consumer<integer> () {
            @Override public
            void Accept (Integer integer) throws Exception {
                log.i (TAG, "filter->integer=" +integer);
            }
        );
Print results:

04-20 17:42:33.764 3101-3101/org.jan.rxandroiddemo i/simplefunc1activity:filter->integer=5
04-20 17:42:33.764 3101-3101/org.jan.rxandroiddemo i/simplefunc1activity:filter->integer=6


5.take operator, limiting the number of emission sources emitted, take (3) means only 3-time elements can be fired

Integer[] array = {1,2,7,5,6,4,0};
        Flowable.fromarray (Array). Take (3). Subscribe (New consumer<integer> () {
            @Override public
            void Accept ( Integer integer) throws Exception {
                log.i (TAG, "take->integer=" +integer);
            }
        );
Print results:

04-20 17:49:54.784 22016-22016/org.jan.rxandroiddemo i/simplefunc1activity:take->integer=1
04-20 17:49:54.784 22016-22016/org.jan.rxandroiddemo i/simplefunc1activity:take->integer=2
04-20 17:49:54.784 22016-22016/org.jan.rxandroiddemo i/simplefunc1activity:take->integer=7


6.doOnNext method: If we want to do something before the Subscriber receives the data, such as logging.

Integer[] array = {1,2,3,5,6,4,0};
        Flowable.fromarray (Array). Doonnext (New consumer<integer> () {
            @Override public
            void Accept (Integer Integer) throws Exception {
                //can be logged before subscription
                log.i (TAG, "doonnext->integer=" +integer);
            }
        ). Subscribe (new consumer<integer> () {
            @Override public
            void Accept (Integer integer) throws Exception {
                log.i (TAG, "subscribe->integer=" +integer);
            }
        );
Print results:

04-20 17:51:57.324 22016-22016/org.jan.rxandroiddemo i/simplefunc1activity:doonnext->integer=1 04-20 17:51:57.324 22016-22016/org.jan.rxandroiddemo i/simplefunc1activity:subscribe->integer=1 04-20 17:51:57.324 22016-22016/org.jan.rxandroiddemo i/simplefunc1activity:doonnext->integer=2 04-20 17:51:57.324 22016-22016/ Org.jan.rxandroiddemo i/simplefunc1activity:subscribe->integer=2 04-20 17:51:57.324 22016-22016/ Org.jan.rxandroiddemo i/simplefunc1activity:doonnext->integer=3 04-20 17:51:57.324 22016-22016/ Org.jan.rxandroiddemo i/simplefunc1activity:subscribe->integer=3 04-20 17:51:57.324 22016-22016/ Org.jan.rxandroiddemo i/simplefunc1activity:doonnext->integer=5 04-20 17:51:57.324 22016-22016/ Org.jan.rxandroiddemo i/simplefunc1activity:subscribe->integer=5 04-20 17:51:57.324 22016-22016/ Org.jan.rxandroiddemo i/simplefunc1activity:doonnext->integer=6 04-20 17:51:57.324 22016-22016/ Org.jan.rxandroiddemo i/simplefunc1activity:subscribe->integer=6 04-20 17:51:57.324 22016-22016/org.jan.rxandroiddemo i/simplefunc1activity:doonnext->integer=4 04-20 17:51:57.324 22016-22016/org.jan.rxandroiddemo i/simplefunc1activity:subscribe->integer=4 04-20 17:51:57.324 22016-22016/ Org.jan.rxandroiddemo i/simplefunc1activity:doonnext->integer=0 04-20 17:51:57.324 22016-22016/
 Org.jan.rxandroiddemo i/simplefunc1activity:subscribe->integer=0

Write today so some, anyway is the basic use, you reader first digest it.


Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

11.11 Big Sale for Cloud

Get Unbeatable Offers with up to 90% Off,Oct.24-Nov.13 (UTC+8)

Get It Now >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.