preface

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

If you are not familiar with RxJava, check out Android: a clear and easy-to-understand introduction to RxJava

  • Today, I’m going to bring youRxjavaThe basic use of &Practical application case teaching, i.e.,Implementation of common development application scenariosAnd combined with commonly used related frameworks such asRetrofitAnd so on. I hope you like it.
  1. This series of articles is based onRxjava 2.0
  2. 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


1. Introduction

RxJava is described below


2. Basic usage

  • Rxjava can be used in two ways: Method 1: Step by step

    Method 2: Chain invocation based on event flow

  • See the article Android RxJava: A Beginner’s Guide to Using RxJava


3. Actual development and application scenarios

  • RxJavaThe actual development and application scenarios are closely related to their corresponding operators
  • commonRxJavaThe actual development and application scenarios are as follows:

  • Below, I will teach each of the actual development application scenarios by example

The examples below all combine common frameworks such as Retrofit, RxBinding, RxBus, etc

3.1 Network Request Polling (Unconditional)

  • Demand scenarios

  • Android RxJava application :(unconditional) network request polling


3.2 Network Request Polling (Conditional)

  • Demand scenarios
  • Specific implementation of Android RxJava practical application explanation :(conditional) network request polling

3.3 Network Request Error Reconnection

  • Demand scenarios

  • Description of Functional Requirements

  • Functional logic

  • Network request error reconnection (combined with Retrofit)

3.4 Network Request nested callback

  • Context A network request needs to be nested: After the first network request succeeds, another network request needs to be made

If the network request for user registration is sent first, the network request for user login is sent again after the registration is successful

  • It is more complicated to implement network request by collision nesting, that is, nesting call function

The basic usage of Retrofit combined with RxJava is shown below, i.e. before the operator is used

// Send the function method to register the network request private voidregister() {api.register(new RegisterRequest()).subscribeon (schedulers.io ()) // Network requests are made on the IO thread ObserveOn (AndroidSchedulers. MainThread ()) / / back to the main thread to handle the request results. The subscribe (new Consumer < RegisterResponse > () {@ Override public  void accept(RegisterResponse registerResponse) throws Exception { Toast.makeText(MainActivity.this,"Registration successful", Toast.LENGTH_SHORT).show(); login(); // Register successfully, call login method}}, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { Toast.makeText(MainActivity.this,"Registration failed", Toast.LENGTH_SHORT).show(); }}); } // Send the network login request function method private voidlogin() {api.login(new LoginRequest()).subscribeon (schedulers.io ()) // Network requests are made on the IO thread ObserveOn (AndroidSchedulers. MainThread ()) / / back to the main thread to handle the request results. The subscribe (new Consumer < LoginResponse > () {@ Override public void accept(LoginResponse loginResponse) throws Exception { Toast.makeText(MainActivity.this,"Login successful", Toast.LENGTH_SHORT).show(); }}, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { Toast.makeText(MainActivity.this,"Login failed", Toast.LENGTH_SHORT).show(); }}); }Copy the code
  • The solution combines the transformation operator FlatMap () in RxJava2 to implement nested network requests

  • Network request nested callback


3.5 Obtaining cache Data from disk/memory Cache

  • Demand scenarios

  • The logic for retrieving cached data from the disk/memory cache is as follows:

  • Specific implementation of Android RxJava practical application explanation: from the disk/memory cache to obtain cache data


3.6 Merging Data Sources

  • Demand scenarios

  • Function description: To obtain data from two data sources at the same time -> merge data -> unified display to the client

  • Specific implementation of Android RxJava practical application: merge data sources


3.7 Joint Judgment

  • Requirements scenarios require joint judgments of multiple events at the same time

For example, when filling out a form, all the information in the form (name, age, occupation, etc.) must be filled in before clicking the “Submit” button

  • Function Description Filling in the form is used here as the joint judgment function display, that is, only after all the information in the form (name, age, occupation, etc.) has been filled in, can you click the “submit” button

  • Specific implementation of Android RxJava practical application: joint judgment


3.8 Thread Control (Switching/scheduling)

  • In the requirement scenario, a new worker thread is opened to perform time-consuming operations; After the execution is complete, switch to the main thread for real-time updateUI
  • Implementation of Android RxJava: Thread control (switching/scheduling)

3.9 Function shake prevention

  • Demand scenarios

  • Functional specifications

  • Specific implementation of Android RxJava practical application explanation: function of anti-shake

3.10 Lenovo search optimization

  • Demand scenarios

  • Functional specifications

  • Specific implementation of Android RxJava practical application: Lenovo search optimization

3.11 Control the rate at which the observed sends events and the observer receives events: back pressure

A. background

  • There are two subscription relationships between observer and observed: synchronous and asynchronous. Details are as follows:

  • For asynchronous subscriptions, there is a mismatch between the speed at which the observed sends events and the speed at which the observer receives them
  1. Send & Receive event rate = number of send & receive events per unit of time
  2. In most cases, the rate at which the observer sends events is greater than the rate at which the observer receives events

B. conflict

  • The speed at which the observed sends events is too fast, and the observer cannot receive all the events, so the observer cannot respond/process all the sent events in time, resulting in overflow of cache and event loss & OOM
  1. For example, click button event: click button 10 times continuously too fast, will only cause the effect of clicking 2 times;
  2. Explanation: Because the speed of the click is too fast, so the button does not respond

Here’s another example:

  • The sending event speed of the observed = 10ms/piece
  • The receiving event rate of the observer = 5s/unit

That is, there is a serious mismatch between send and receive events

Observable.create(new ObservableOnSubscribe<Integer>() { // 1. @override Public void subscribe(ObservableEmitter<Integer> Emitter) throws Exception {for (int i = 0; ; i++) {
                    Log.d(TAG, "Event sent"+ i ); Thread.sleep(10); // Emitters are emitter. OnNext (I); }}}). SubscribeOn (Schedulers. IO ()) / / set the observed in IO thread. ObserveOn (AndroidSchedulers. MainThread ()) / / set the observer in the main thread .subscribe(new Observer<Integer>() { // 2. Override public void onSubscribe(Disposable d) {Log."Start using subscribe connections."); } @override public void onNext(Integer value) {try {thread.sleep (5000); Log.d(TAG,"Event received"+ value  );
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }

            @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
  • Results As the speed of the event sent by the observer is greater than the speed of the event received by the observer, the velocity mismatch occurs, resulting inOOM

C. The solution uses the back pressure policy

  • Specific implementation of Android: comprehensive analysis of RxJava back pressure strategy

At this point, the practical application scenarios of common RxJava development are explained.


4. To summarize

  • This paper mainly focuses onRxJava2The common practical development and application scenarios are introduced in detail. The following is a summary with a picture

  • 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!!


Thumbs up for top/comment! Because your encouragement is the biggest power that I write!


Welcome to follow Carson_ho on wechat