preface
-
Rxjava
Due to itsChain call based on event flow, simple logic & easy to useThe characteristics of the deepAndroid
Developer welcome.
- This paper mainly:
- Rigid contact oriented
Rxjava
beginners - Provides a clear, concise, easy to understand Rxjava introduction tutorial
Covers basic introduction, principle & specific use, etc
- The solution is that beginners don’t understand
Rxjava
Principle & Do not know how to use the problem
- Rigid contact oriented
I hope you like it.
- This paper is mainly based on
Rxjava 2.0
- If you haven’t already
Rxjava 1.0
And it doesn’t matter becauseRxjava 2.0
Only in theRxjava 1.0
A few new features have been added, essentially the same principle & usage- 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.
-
RxJava
在GitHub
Introduction:
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 programsCopy the code
- Conclusion:
RxJava
Is 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 & explain
Rxjava
Principle:Customers go to restaurants to eat
4.2 Principles of Rxjava
-
Rxjava
Based on the principle ofAn extended observer model
See article XXX for the observer pattern
-
Rxjava
There are four roles in 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 on
RxJava
Basic use of more in-depthRxJava
Use please continue to pay attentionCarson_Ho android Development Notes -
Rxjava
There are two ways to use:- Step by step: This method is mainly for further explanation
Rxjava
Principle & Use,Mainly used for illustration - Chain call based on event flow: mainly for practical use
- Step by step: This method is mainly for further explanation
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"); // 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:
Next
Events,Complete
Event &Error
Events. 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
5.2 Approach 2: Elegant implementation method – chain call based on event flow
- The above implementation is intended to illustrate
Rxjava
Principle & 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.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 every time an Observable event is received 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
The compile 'IO. Reactivex. Rxjava2: rxjava: 2.0.1' compile 'IO. Reactivex. Rxjava2: rxandroid: 2.0.1'Copy the code
Step 2: Directly inMainActivity.java
To implement the following steps
- Create observed
(observables)
& Production incident - Create observer
(the Observer)
And define the behavior in response to the event - 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 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
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 "); }}); }}Copy the code
-
Test effect to achieve the same effect
Schematic diagram -
Github address of Carson_Ho = RxJava2 series: basic use
7. Additional notes
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
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 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
8. To summarize
- This paper mainly focuses on
Rxjava
Introduction 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!
The Android event distribution mechanism is the most comprehensive and easy to understand solution for Android screen adaptation. It is the most comprehensive and easy to understand solution for Android screen adaptation. Android development: JSON introduction and the most comprehensive analysis method! BroadcastReceiver Is the most comprehensive version of Android’s BroadcastReceiver
Welcome to attentionCarson_HoJane books!
Share the dry things about Android development from time to time, the pursuit of short, flat, fast, but there is no lack of depth.