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

  • RxjavaThere are two ways to use:

    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 following examples are combined with common frameworks such as
    Retrofit
    RxBinding,
    RxBusEtc.

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

Private void register() {api.register(new RegisterRequest()).subscribeon (schedulers.io ()) / / requests for network on 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, "Registered successfully ", 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(); }}); } private void login() {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 succeeded ", 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

  • Functional specifications

    The functional logic for fetching 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 in the 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)

  • Demand scenarios

    That is, 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 isA mismatch between the speed at which an observer sends an event and the speed at which the observer receives an event


    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
  • For example, click button event: click button 10 times continuously too fast, will only cause the effect of clicking 2 times;
  • Explanation: Because the speed of the click is too fast, so the button does not respond
    • 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, "sent event "+ 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. D (TAG, "subscribe "); } @override public void onNext(Integer value) {try {thread.sleep (5000); Log.d(TAG, "received event "+ value); } catch (InterruptedException e) { e.printStackTrace(); }} @override public void onError(Throwable e) {log. d(TAG, "response to Error "); } @override public void onComplete() {log.d (TAG, "response to Complete event "); }});Copy the code
    • The results of

      As the speed of the event sent by the observer is greater than the speed of the event received by the observer, there is a velocity mismatch problem, 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!