Author: Carson_Ho

Address: http://www.jianshu.com/p/a406b94f3188

Disclaimer: This article is written by Carson_Ho and has been published with permission. Please do not reprint it without the permission of the original author

preface

  • Rxjava is popular among Android developers because of its chain call based on event flow, simple logic and easy to use.

This paper mainly:

1, for beginners who just contact Rxjava

2, provides a clear, concise, easy to understand Rxjava introduction tutorial

3, the solution is beginners do not understand Rxjava principle & do not know how to use the problem

I hope you like it

1. This article is mainly based on Rxjava 2.0

2. If you haven’t already learned Rxjava 1.0, it doesn’t matter, because Rxjava 2.0 just adds some new features to Rxjava 1.0

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 and so on. If you are interested, you can continue to pay attention to Carson_Ho’s Android development notes!!

directory

define

  • RxJava on GitHub

RxJava: A library for composing Asynchronous and Event-based programs using Observable sequences for the Java VM

RxJava is a library that uses observable sequences on the Java VM to compose asynchronous, event-based programs

  • Summary: RxJava is an event-based library that implements asynchronous operations

role

Implementing asynchronous operations

Similar to Android AsyncTask, Handler function

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

The principle of

4.1 Introduction of life examples

  • I introduce and explain the principle of Rxjava with a life example: a customer comes to a restaurant 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.

The basic use

  • This article focuses only on the basic use of RxJava. For more in-depth use of RxJava, please stay tuned to Carson_Ho’s Android development notes

  • Rxjava can be used in two ways:

  1. Step by step implementation: this method is mainly for in-depth explanation of Rxjava principle & use, mainly used for demonstration

  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

// 1. Create the observed Observable

Observable<Integer> Observable = ObservableOnSubscribe (new ObservableOnSubscribe<Integer>() {// Create () is RxJava The basic method for creating a sequence of events // passes an OnSubscribe object argument // 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”); // onNext(“A”); // onNext(“B”); // onNext(“C”); // onCompleted(); From (T[])/from(Iterable<? Extends T>) : Extends String[] words = {“A”, “B”, “C”}; extends T>) : Extends String[] words = {“A”, “B”, “C”}; Observable observable = Observable.from(words); // onNext(“A”); // onNext(“B”); // onNext(“C”); // onCompleted();

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: Next event, Complete event & Error event. 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. D (TAG, “subscribe “); } // When the observer produces the Next event & the observer receives, @override public void onNext(Integer value) {log. d(TAG, “respond to Next event” + value); Override public void onError(Throwable e) {log. d(TAG, “response to Error “); } // Override public void onComplete() {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, “subscribe “); } // When the observer produces the Next event & the observer receives, @override public void onNext(Integer value) {log. d(TAG, “respond to Next event” + value); Override public void onError(Throwable e) {log. d(TAG, “response to Error “); } // Override public void onComplete() {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 occur

    Subscribe

    Namely customer find waiter – order – waiter order to the kitchen – kitchen cooking

    The specific implementation

    observable.subscribe(observer); // Or observable.subscribe(subscriber);

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

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

  • The above implementation is to illustrate the principle & use of Rxjava

  • In practice, the above steps & code would be linked together to make it more concise and elegant, called RxJava event-based chain calls

// RxJava chain operations

Observable.create(new ObservableOnSubscribe

() { // 1. @override Public void subscribe(ObservableEmitter

Emitter) throws Exception {emitter. OnNext (1); emitter.onNext(2); emitter.onNext(3); emitter.onComplete(); } }).subscribe(new Observer

() { // 2. By connecting the observer to the observed via subscribe // 3. Override public void onSubscribe(Disposable d) {Log. D (TAG, “subscribe “); Override public void onNext(Integer value) {log.d (TAG, “Next event “+ value +” response”); } @override public void onError(Throwable e) {log.d (TAG, “response to Error “); } @override public void onComplete() {log.d (TAG, “response to Complete event “); }}); OnSubscribe () > subscribe () > watcher.onNext () > watcher.oncomplete ()


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.xA number of functional interfaces are provided to implement the simple observer mode. Details are as follows:

Take Consumer as an example: Implement the simple observer mode

Observable.just(“hello”).subscribe(new Consumer<String>() {

Void Accept (String s) throws Exception {// Call Consumer.accept () @override public void Accept (String s) throws Exception { System.out.println(s); }});

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

Example is given to illustrate

6.1 Method 1: Step by step

Step 1: Add dependencies

The compile ‘IO. Reactivex. Rxjava2: rxjava: 2.0.1’

The compile ‘IO. Reactivex. Rxjava2: rxandroid: 2.0.1’

Step 2: Directly inMainActivity.javaTo implement the following steps

  1. Create observables & produce events

  2. Create observers and define the behavior of responding to events

  3. The observer is connected to the observed by subscribing

    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 subscribe (Disposable d) {Log. D (” subscribe “); Override public void onNext(Integer value) {log.d (TAG, “Next event “+ value +” response”); } @override public void onError(Throwable e) {log.d (TAG, “response to Error “); } @override public void onComplete() {log.d (TAG, “response to 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.

  • 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. D (TAG, “subscribe “); Override public void onNext(Integer value) {log.d (TAG, “Next event “+ value +” response”); } @override public void onError(Throwable e) {log.d (TAG, “response to Error “); } @override public void onComplete() {log.d (TAG, “response to Complete event “); }}); }}

  • Test effect to achieve the same effect

  • Demo download address of Carson_Ho making = RxJava2 series: basis of use: https://github.com/Carson-Ho/RxJava_Operators

Like trouble point a star!

Additional instructions

Subscribe () has multiple overloaded methods

public final Disposable subscribe() {}

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 observed

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

    // This is implemented in the Observer

    Observer<Integer> observer = new Observer<Integer>() { // 1. Private Disposable mDisposable; @override public void subscribe (Disposable d) {Log. D (” subscribe “); // 2. Assign mDisposable = d to Disposable; } @override public void onNext(Integer value) {log. d(TAG, “Next event “+ value +” response”); Dispose () if (value == 2) {// Dispose () disconnects the observer and the observed after receiving the second event. Log. D (TAG, “Already disposed:” + mDisposable. IsDisposed ()); }} @override public void onError(Throwable e) {log. d(TAG, “response to Error “); } @override public void onComplete() {log.d (TAG, “response to Complete event “); }};

  • rendering

  • This article mainly introduces the basic knowledge of Rxjava, including basic introduction, principle & 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!!

Recommended reading

1, Android Studio3.0 update road (in the pit will enter)

Good confusion, how to start learning?

3. I don’t write a line of code to implement the Toolbar! And you’re still wrapping BaseActivity?