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 it to beginnersRxJavaI 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. RxJava profile

Here is a brief introductionRxJava

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


2. Basic usage

  • This article focuses only onRxJavaBasic use of more in-depthRxJavaUse please continue to pay attentionCarson_Ho’s RxJava family
  • 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

2.1 Method 1: Step by step

2.1.1 Procedure

2.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"); // 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();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. 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 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

2.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. 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 ()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.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>() {// Call consumer.accept () @override public every time an Observable event is received void accept(String s) throws Exception { System.out.println(s); }});Copy the code

3. Examples

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

3.1 Method 1: Step by step

Step 1: Add dependencies

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

Step 2: Implement the following steps directly in mainActivity.java. Observables create observables and produce events. 2. Create observers and define actions that respond to events. 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.Copy the code
  • The test results

3.2 Mode 2: Chain call mode 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 "); }}); }}Copy the code
  • The test results

    The implementation effect is the same as above

  • Github address of Carson_Ho = RxJava2 series: basic use

    Like trouble point a star!


4. Additional notes

4.1 Observer subscribe() has multiple overloaded methods

Public Final Disposable Subscribe () {} public Final Disposable subscribe() {} public Final Disposable subscribe() {} public Final Disposable subscribe() { 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

4.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 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 "); }};Copy the code
  • rendering

This concludes the basic use of RxJava.


5. To summarize

  • This paper mainly explainsRxjavaFor more examples, see the article:When should you use RxJava?
  • 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!!


Please give the top/comment a thumbs up! Because your encouragement is the biggest power that I write!