preface

  • RxjavaDue to itsChain call based on event flow, simple logic & easy to useThe characteristics of the deepAndroidDeveloper welcome.

  • This paper mainly:
    1. Rigid contact orientedRxjavabeginners
    2. Provides a clear, concise, easy to understand Rxjava introduction tutorial

    Covers basic introduction, principle & specific use, etc

    1. The solution is that beginners don’t understandRxjavaPrinciple & Do not know how to use the problem

I hope you like it.

  1. This paper is mainly based onRxjava 2.0
  2. If you haven’t alreadyRxjava 1.0And it doesn’t matter becauseRxjava 2.0Only in theRxjava 1.0A few new features have been added, essentially the same principle & usage
  3. In the coming days, I will continue to publish a series of articles on Rxjava 2.0 in Android, including principles, operators, application scenarios, back pressure, etc. If you are interested, please continue to follow Carson_Ho’s Android development notes!!


directory


Definition 1.

  • RxJavaGitHubIntroduction:
RxJava: a libraryfor composing asynchronous and event-based programs using observable sequences forRxJava is a library that uses observable sequences on the Java VM to compose asynchronous, event-based programsCopy the code
  • Conclusion:RxJavaIs aAsynchronous operation based on event flowIn the library

2. The role

Implementing asynchronous operations

Similar to Android AsyncTask, Handler function


Characteristics of 3.

Since RxJava is used as a chain call based on event flow, it makes RxJava:

  • Logic is concise
  • To achieve elegant
  • Using a simple

More importantly, as the complexity of the program logic increases, it remains simple and elegant


Principle 4.

4.1 Introduction of life examples

  • I use a life example to introduce & explainRxjavaPrinciple:Customers go to restaurants to eat

4.2 Principles of Rxjava

  • The Rxjava principle is based on an extended observer pattern

  • There are four roles in Rxjava’s extended Observer mode:

role role analogy
Observable Generate events The customer
An Observer Receives the event and gives the response action The kitchen
Subscribe Connect the observed with the observer The waiter
Event The carrier of communication between the observed and the observer dishes
  • Specific principles

Customers go to restaurants to have a meal.

That is, the principle of RxJava can be summarized as follows: Observable sends events to observers in order by subscribing, and the Observer receives events in order & makes corresponding response actions. The details are as follows:

At this point, RxJava principle is finished.


Basic use

  • This article focuses only onRxJavaBasic use of more in-depthRxJavaUse please continue to pay attentionCarson_Ho android Development Notes
  • RxjavaThere are two ways to use:
    1. Step by step: This method is mainly for further explanationRxjavaPrinciple & Use,Mainly used for illustration
    2. Chain call based on event flow: mainly for practical use

5.1 Method 1: Step by step

5.1.1 Procedure

5.1.2 Procedure Details
Step 1: Create observed (Observable) & Production events
  • That is, when a customer enters a restaurant, sits down at a table and orders
  • The specific implementation
Observable<Integer> Observable = Observable. Create (new ObservableOnSubscribe<Integer>() {// 1 Create () is the basic RxJava method for creating event sequences. // An OnSubscribe object is passed in. // The OnSubscribe call() method is automatically called when an Observable is subscribed. That is, the sequence of events will be triggered in sequence according to the setting // that is, the observer will call the corresponding event copy method in order to respond to the event // So as to realize the observer called the observer callback method & by the observed to the observer event transmission, that is, the observer mode // 2. @override public void subscribe(ObservableEmitter<Integer> Emitter) throws Exception {// Pass ObservableEmitter class object generates events and notifies the observer. OnNext (1); Emitters. OnNext (1); Emitters. emitter.onNext(2); emitter.onNext(3); emitter.onComplete(); }}); <-- extension: RxJava provides other methods to create an Observable --> Observable Observable = Observable. Just ("A"."B"."C"); // will call: // onNext("A");
  // onNext("B");
  // onNext("C"); // onCompleted(); From (T[])/from(Iterable<? Extends T>) : Divides an array/Iterable into concrete objects and sends them out in turn."A"."B"."C"}; Observable observable = Observable.from(words); // will call: // onNext("A");
  // onNext("B");
  // onNext("C");
  // onCompleted();

Copy the code
Step 2: Create an observer (Observer) and define the behavior in response to the event
  • Open the kitchen. – Determine the dishes
  • The types of events that occur include:NextEvents,CompleteEvent &ErrorEvents. Details are as follows:

  • The specific implementation
< p style = "box-sizing: border-box! Important; word-wrap: break-word! Important; Observer<Integer> Observer = new Observer<Integer>() {// 2. Create objects that respond to corresponding events by copying corresponding events // Before the observer receives the event, Override public void subscribe (Disposable d) {Log."Start using subscribe connections."); } // Override public void onNext(Integer value) {log.d (TAG, TAG, TAG, TAG, TAG, TAG, TAG, TAG, TAG, TAG, TAG, TAG, TAG, TAG, TAG"Respond to the Next event"+ value); } @override public void onError(Throwable e) {log.d (TAG, Throwable e) {Override public void onError(Throwable e) {Log."Respond to an Error event"); } // When the observer produces a Complete event & the observer receives it, the Override method is called in responseonComplete() {
                Log.d(TAG, "Respond to the Complete Event"); }}; <-- Mode 2: use Subscriber abstract class --> // Description: Subscriber class = RxJava a built-in abstract class that implements Observer and extends the Observer interface // 1. Subscriber<String> Subscriber = new Subscriber<Integer>() {// 2. Create objects that respond to corresponding events by copying corresponding events // Before the observer receives the event, Override public void subscribe (Subscription s) {log.d (TAG, TAG, TAG)"Start using subscribe connections."); } // Override public void onNext(Integer value) {log.d (TAG, TAG, TAG, TAG, TAG, TAG, TAG, TAG, TAG, TAG, TAG, TAG, TAG, TAG, TAG"Respond to the Next event"+ value); } @override public void onError(Throwable e) {log.d (TAG, Throwable e) {Override public void onError(Throwable e) {Log."Respond to an Error event"); } // When the observer produces a Complete event & the observer receives it, the Override method is called in responseonComplete() {
                Log.d(TAG, "Respond to the Complete Event"); }}; <-- pay special attention to the difference between the Subscriber abstract class and the Observer interface --> The Subscriber abstract class extends the Observer interface by adding two new methods: // 1. onStart() : called before an event has been responded to, to do some initialization work // 2. unsubscribe() : to unsubscribe. Before invoking the method, isUnsubscribed() is used to determine whether the observed Observable still holds observer Subscriber references. If the references are not released in time, memory leaks may occurCopy the code
Step 3: By subscribingSubscribe) connects the observer and the observed
  • Namely customer find waiter – order – waiter order to the kitchen – kitchen cooking
  • The specific implementation
observable.subscribe(observer); // Or observable.subscribe(subscriber);Copy the code
  • Extension instructions
<-- Observable. Subscribe (Subscriber) --> public Subscription (Subscriber) { subscriber.onStart(); // Override method of the observer subscriber abstract class in Step 1, which is used to initialize the job onsubscribe.call (subscriber); // By calling the corresponding method in the observer to respond to the event produced by the observer // To implement the observer called the observer callback method & by the observer to the observer event pass, namely the observer mode // Also see: An Observable only produces events, and actually sends events when it subscribes, when the subscribe() method executes}.Copy the code

5.2 Approach 2: Elegant implementation method – chain call based on event flow

  • The above implementation is intended to illustrateRxjavaPrinciple & use of
  • In practice, the above steps & code would be linked together to make it more concise and elegant, called RxJava event-based chain calls
Observable. Create (new ObservableOnSubscribe<Integer>() {// 1. @override Public void subscribe(ObservableEmitter<Integer> Emitter) throws Exception {emitter. OnNext (1); emitter.onNext(2); emitter.onNext(3); emitter.onComplete(); } }).subscribe(new Observer<Integer>() { // 2. By connecting the observer to the observed via subscribe // 3. Override public void onSubscribe(Disposable d) {Log."Start using subscribe connections."); Override public void onNext(Integer value) {log.d (TAG, TAG) {subscribe () @override public void onNext(Integer value) {Log."To the Next event"+ value +"Respond"  );
            }

            @Override
            public void onError(Throwable e) {
                Log.d(TAG, "Respond to an Error event");
            }

            @Override
            public void onComplete() {
                Log.d(TAG, "Respond to the Complete Event"); }}); OnSubscribe () > subscribe () > watcher.onNext () > watcher.oncomplete ()Copy the code

This event-based chain call allows RxJava to:

  • Logic is concise
  • To achieve elegant
  • Using a simple

More importantly, as the complexity of the program logic increases, it remains simple and elegant. Therefore, it is generally recommended to implement RxJava using this event-based chain invocation approach.

Pay special attention to

RxJava 2.x provides a number of functional interfaces for implementing the simple Observer pattern. Details are as follows:

Take Consumer as an example: Implement the simple observer mode

Observable.just("hello"Subscribe (new Consumer<String>() {// Call consumer.accept () @override public void Accept (String s). throws Exception { System.out.println(s); }});Copy the code

6. Examples

I’ll demonstrate the use of Rxjava with a real project example

6.1 Method 1: Step by step

Step 1: Add dependencies

    compile 'the IO. Reactivex. Rxjava2: rxjava: 2.0.1'
    compile 'the IO. Reactivex. Rxjava2: rxandroid: 2.0.1'
Copy the code

Step 2: Directly inMainActivity.javaTo implement the following steps

  1. Create observed(observables)& Production incident
  2. Create observer(the Observer)And define the behavior in response to the event
  3. By subscribing to(Subscribe)Connect the observer and the observed
public class MainActivity extends AppCompatActivity {

    private static final String TAG = "Rxjava";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); Observable Observable Observable Observable Observable Observable Observable Observable Observable Observable Observable Observable Observable<Integer> Observable = ObservableOnSubscribe<Integer>() {// 2. @override public void subscribe(ObservableEmitter<Integer> Emitter) throws Exception {// Pass ObservableEmitter class object generates events and notifies the observer. OnNext (1); Emitters. OnNext (1); Emitters. emitter.onNext(2); emitter.onNext(3); emitter.onComplete(); }}); // Step 2: Observer<Integer> Observer = new Observer<Integer>() {// Respond to the observed by copying the corresponding method @Override public void onSubscribe(Disposable d) { Log.d(TAG,"Start using subscribe connections."); Override public void onNext(Integer value) {log.d (TAG, TAG) {subscribe () @override public void onNext(Integer value) {Log."To the Next event"+ value +"Respond"  );
            }

            @Override
            public void onError(Throwable e) {
                Log.d(TAG, "Respond to an Error event");
            }

            @Override
            public void onComplete() {
                Log.d(TAG, "Respond to the Complete Event"); }}; // The customer finds the waiter -- orders -- the waiter orders to the kitchen -- the kitchen cooks observable. Subscribe (observer); // The customer finds the waiter -- orders -- the waiter orders to the kitchen -- the kitchen cooks observable.Copy the code
  • The test results

6.2 Mode 2: Chain invocation based on event flow

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "Rxjava";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); Observable. Create (new ObservableOnSubscribe<Integer>() {// 1. @override Public void subscribe(ObservableEmitter<Integer> Emitter) throws Exception {emitter. OnNext (1); emitter.onNext(2); emitter.onNext(3); emitter.onComplete(); } }).subscribe(new Observer<Integer>() { // 2. By connecting the observer to the observed via subscribe // 3. Override public void onSubscribe(Disposable d) {Log."Start using subscribe connections."); Override public void onNext(Integer value) {log.d (TAG, TAG) {subscribe () @override public void onNext(Integer value) {Log."To the Next event"+ value +"Respond"  );
            }

            @Override
            public void onError(Throwable e) {
                Log.d(TAG, "Respond to an Error event");
            }

            @Override
            public void onComplete() {
                Log.d(TAG, "Respond to the Complete Event"); }}); }}Copy the code
  • Test effect to achieve the same effect

  • Github address of Carson_Ho = RxJava2 series: basic use

Like trouble point a star!


7. Additional notes

Subscribe () has multiple overloaded methods

    public final Disposable subscribe() {} public final Disposable Subscribe (Consumer<? Super T> onNext) {} public final Disposable subscribe(Consumer<? super T> onNext, Consumer<? Super Throwable> onError) {} public final Disposable subscribe(Consumer<? super T> onNext, Consumer<? super Throwable> onError, Action onComplete) {} public Final Disposable subscribe(Consumer<? super T> onNext, Consumer<? super Throwable> onError, Action onComplete, Consumer<? Super Disposable> onSubscribe) {} public final void super Disposable> onSubscribe public final void super Disposable> onSubscribe public final void super Disposable> onSubscribe subscribe(Observer<? Super T> observer) {} // Indicates that the observer responds to any event sent by the observedCopy the code

7.2 Disposable.Dispose () can be used to cut off the connection between the observer and the observed

  • That is, the observer cannot continue to receive events from the observed, but the observed can continue to send events
  • The specific use
Observer<Integer> Observer = new Observer<Integer>() {// 1. Private Disposable mDisposable; @Override public void onSubscribe(Disposable d) { Log.d(TAG,"Start using subscribe connections."); // 2. Assign mDisposable = d to Disposable; } @Override public void onNext(Integer value) { Log.d(TAG,"To the Next event"+ value +"Respond"  );
                if(value == 2) {// Dispose () disconnects the observer and the observed after receiving the second event. Log.d(TAG,"The connection has been severed:" + mDisposable.isDisposed());
                }
            }

            @Override
            public void onError(Throwable e) {
                Log.d(TAG, "Respond to an Error event");
            }

            @Override
            public void onComplete() {
                Log.d(TAG, "Respond to the Complete Event"); }};Copy the code
  • rendering


8. To summarize

  • This paper mainly focuses onRxjavaIntroduction of knowledge, including basic introduction, principles & specific use
  • Next, I will continue to publish a series of articles on Rxjava 2.0 in Android, including principles, operators, application scenarios, back pressure, etc. If you are interested, please continue to pay attention to Carson_Ho Android development notes!!


Thumb up, please! Because your encouragement is the biggest power that I write!


Welcome to follow Carson_ho on wechat