RxJava simple learning (learning self-throwing things)

Source: Internet
Author: User

RxJava simple learning (learning self-throwing things)

 

Preface

At present, RxJava is getting increasingly popular, and more people are learning RxJava. More and more projects are using RxJava, so we need to learn RxJava.

What is RxJava? What is Rx?

RX (Reactive Extensions) was originally proposed by Microsoft to integrate asynchronous and opportunity event-driven library packages, using open observation sequences and LINQ-style query operations. What are the characteristics of RX? The most notable feature of Rx is the use of the Observable Collection to achieve integrated asynchronous (composing asynchronous) and event-based programming. Of course, the sequence in RX is data stream. We will not talk about this much. RX introduction.

What is RxJava?

RxJava is an open-source project developed and maintained by ReactiveX. Let's take a look at ReactiveX introduction.

ObviouslyAsynchronous programmingNext, let's take a look at the introduction of RxJava.

A Java VM uses an observed sequence to form an asynchronous, event-based program library. It is a bit abstract. In other words, it is the observer mode, asynchronous mode, and event stream. RxJava is a responsive programming. Responsive programming

Observer mode. For example? For example, if you have a nap and don't go to bed, you can say "XX". When it comes to calling me, and then when the time is up, he will wake you up. This is a very simple example. I will not elaborate on the observer mode. What is asynchronous? You don't know what Asynchronization is? Then how do you learn programming. Asynchronous means that execution can continue without waiting for the result. Here we draw up the concept of callback. The event stream is a series of ordered events. How to Use RxJava?

It is introduced in AS now.

compile 'io.reactivex:rxjava:1.0.16'compile 'io.reactivex:rxandroid:1.0.1'

The reason why RxAndroid is introduced here is the android program.

1. Observer

The following two methods are available.

public static Observer getObserver(){        Observer
  
    observer = new Observer
   
    () {            @Override            public void onCompleted() {                Log.e(TAG, "onCompleted: " );            }            @Override            public void onError(Throwable e) {                Log.e(TAG, "onError: "+e.getMessage() );            }            @Override            public void onNext(String s) {                Log.e(TAG, "onNext: "+s );            }        };        return observer;    }
   
  
public static Observer getSubscriber(){        Subscriber
  
    subscriber = new Subscriber
   
    () {            @Override            public void onCompleted() {                Log.e(TAG, "onCompleted: " );            }            @Override            public void onError(Throwable e) {                Log.e(TAG, "onError: " );            }            @Override            public void onNext(String s) {                Log.e(TAG, "onNext: "+s );            }        };        return subscriber;    }
   
  

The relationship between the two is as follows:

OnCompleted event stream ends onError onNext event normal
These three are the callbacks triggered when an event occurs. In android, callback usually occurs in the UI thread. 2. Observable

The source code of Observable is 1 w + lines. We generally use the following three methods to create the observer.

2.1.Create
Observable observable = Observable.create(new Observable.OnSubscribe
  
   () {            @Override            public void call(Subscriber
    subscriber) {                subscriber.onNext("hello");                subscriber.onNext("world");                subscriber.onNext("my name is quanshijie");                subscriber.onCompleted();            }        });
  

OnNext is an event. This method must end with onCompleted.

2.2.just
Observable observable = Observable.just("hello", "world", "my name is quanshijie");

Just is an event.

2.3.form
String[] words = {"hello","world","my name is quanshijie"};Observable observable = Observable.from(words);
3. Subscribe

Observable. subscribe (Observable or Subscriber)
You can also use the following method.

observable.subscribe(new Action1
  
   () {                                 @Override                                 public void call(String s) {                                     Log.e(TAG, "call: " + s);                                 }                             }, new Action1
   
    () {                                 @Override                                 public void call(Throwable throwable) {                                     Log.e(TAG, "call: " + throwable.getMessage());                                 }                             }, new Action0() {                                 @Override                                 public void call() {                                     Log.e(TAG, "call: "+"completed" );                                 }                             }        );
   
  
4. Thread Scheduling

In android, switching between threads is frequent, and UI threads cannot perform time-consuming operations. In android, there are still many time-consuming operations. Let's take a look at how to perform thread scheduling. See the following example.

Observable. just (1, 2, 3, 4 ). subscribeOn (Schedulers. io () // subscribe occurs in the IO thread. observeOn (AndroidSchedulers. mainThread () // specifies that the callback occurs in the main thread. subscribe (new Action1
  
   
() {@ Override public void call (Integer integer) {Log. e (TAG, "call:" + integer );}});
  

Assume that 1, 2, 3, and 4 are time-consuming operations, such as database operations, network requests, or other operations. We use subscribeOn to specify the thread where these events occur and observeOn to specify the callback thread,

Scheduler. io () io thread Scheduler. newThread new thread schedate. immediate current thread AndroidSchedulers. mainThread () androidUI thread 5. Transform 5.1 map Transform
Observable.just("xxx")                .map(new Func1
  
   () {                    @Override                    public Bitmap call(String s) {                        return BitmapFactory.decodeFile(s);                    }                })                .subscribe(new Action1
   
    () {                    @Override                    public void call(Bitmap bitmap) {//                        showBitmap(bitmap);                    }                });
   
  

Funcx function to implement type conversion. Here is a one-to-one conversion

5.2 flatMap Conversion

Implement many-to-many conversion. Let's look at the parabolic example.

Student[] students = ...;Subscriber
  
    subscriber = new Subscriber
   
    () {    @Override    public void onNext(Course course) {        Log.d(tag, course.getName());    }    ...};Observable.from(students)    .flatMap(new Func1
    
     >() {        @Override        public Observable
     
       call(Student student) {            return Observable.from(student.getCourses());        }    })    .subscribe(subscriber);
     
    
   
  
When to use RxJava

After talking about so many RxJava usage, there is nothing to use. If we say so much, it will be useless in the end. For usage instructions, refer to RxJava's usage summary or the rxdemo on github.

Summary

Other ready-made Observable such as RxJava + retrofit + lambda + RxBinding will make our code concise, clean, and clear.

Related 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.