Source code analysis of Rxjava 2

From Demo to Principle

    Observable.create(new ObservableOnSubscribe() {
    
    
            @Override
            public void subscribe(ObservableEmitter e) throws Exception {
    
    
                e.onNext(1);

                e.onNext(2);

                e.onNext(3);

                e.onComplete();


            }
        }).subscribe(new Observer<Integer>() {
    
    
          @Override
          public void onSubscribe(Disposable d) {
    
    
              Log.d("MainActivity:","onSubscribe()");
          }

          @Override
          public void onNext(Integer i) {
    
    
                Log.d("MainActivity : " ,"onNext =" + i);
          }

          @Override
          public void onError(Throwable e) {
    
    
              Log.d("MainActivity:","onError()");
          }

          @Override
          public void onComplete() {
    
    
              Log.d("MainActivity:","onComplete()");
          }
      });

输出结果:
MainActivity:: onSubscribe()
MainActivity :: onNext =1
MainActivity :: onNext =2
MainActivity :: onNext =3
MainActivity:: onComplete()

As you can see, Observer's onSubscribe is called first. What is the use of this callback? We will talk about it later.
OK, where do I start? Observable.create, well, the whole process starts with create, so let's start from the source. Let's take a look at create first. What he returns is an observable object, which is the object to be observed. The create method needs to pass in an ObservableOnSubscribe to create it. Let's see what ObservableOnSubscribe is:

public interface ObservableOnSubscribe<T> {
    
    

    /**
     * Called for each Observer that subscribes.
     * @param e the safe emitter instance, never null
     * @throws Exception on error
     */
    void subscribe(ObservableEmitter<T> e) throws Exception;
}

ObservableOnSubscribe is obviously an interface with only one method subscribe(). Let's take a look at the parameter type ObservableEmitter in this method:

public interface ObservableEmitter<T> extends Emitter<T> {
    
    

```java
    /**
     * Sets a Disposable on this emitter; any previous Disposable
     * or Cancellation will be unsubscribed/cancelled.
     * @param d the disposable, null is allowed
     */
    void setDisposable(Disposable d);

    /**
     * Sets a Cancellable on this emitter; any previous Disposable
     * or Cancellation will be unsubscribed/cancelled.
     * @param c the cancellable resource, null is allowed
     */
    void setCancellable(Cancellable c);

    /**
     * Returns true if the downstream disposed the sequence.
     * @return true if the downstream disposed the sequence
     */
    boolean isDisposed();

    /**
     * Ensures that calls to onNext, onError and onComplete are properly serialized.
     * @return the serialized ObservableEmitter
     */
    ObservableEmitter<T> serialize();
}




public interface Emitter<T> {
    
    

    /**
     * Signal a normal value.
     * @param value the value to signal, not null
     */
    void onNext(@NonNull T value);

    /**
     * Signal a Throwable exception.
     * @param error the Throwable to signal, not null
     */
    void onError(@NonNull Throwable error);

    /**
     * Signal a completion.
     */
    void onComplete();
}

ObservableEmitter inherits the Emitter class, but it also has a few more methods. This is actually the function introduced after Rxjava 2.0, which provides new capabilities such as canceling halfway. Let’s continue to look at the Emitter class. I believe everyone is interested in these three methods. It should be very familiar, so I won't introduce too much here.
ObservableOnSubscribe is the source of this event stream. We will call it the event source below, which is usually created and passed in by ourselves. When we create it, we need to rewrite its subscribe() method and enter the event production through the passed ObservableEmitter parameter. Seeing this, we only understand the data structure of the passed parameters, and the information we understand is still relatively small. Let's continue to see what operations are done inside create?


Class Observable{
    
    
......
   public static <T> Observable<T> create(ObservableOnSubscribe<T> source) {
    
    
        ObjectHelper.requireNonNull(source, "source is null");
        return RxJavaPlugins.onAssembly(new ObservableCreate<T>(source));
    }
 ......
}

The RxJavaPlugins.onAssembly here uses Hook technology, and here everyone understands it as returning an Observable object. I will mainly take a look at the
ObservableCreate class:

public final class ObservableCreate<T> extends Observable<T> {
    
    
    final ObservableOnSubscribe<T> source;

    public ObservableCreate(ObservableOnSubscribe<T> source) {
    
    
        this.source = source;
    }

    @Override
    protected void subscribeActual(Observer<? super T> observer) {
    
    
        CreateEmitter<T> parent = new CreateEmitter<T>(observer);
        observer.onSubscribe(parent);

        try {
    
    
            source.subscribe(parent);
        } catch (Throwable ex) {
    
    
            Exceptions.throwIfFatal(ex);
            parent.onError(ex);
        }
    }

    static final class CreateEmitter<T>
    extends AtomicReference<Disposable>
    implements ObservableEmitter<T>, Disposable {
    
    


        private static final long serialVersionUID = -3434801548987643227L;

        final Observer<? super T> observer;

        CreateEmitter(Observer<? super T> observer) {
    
    
            this.observer = observer;
        }

        @Override
        public void onNext(T t) {
    
    
            if (t == null) {
    
    
                onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources."));
                return;
            }
            if (!isDisposed()) {
    
    
                observer.onNext(t);
            }
        }

        @Override
        public void onError(Throwable t) {
    
    
            if (t == null) {
    
    
                t = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources.");
            }
            if (!isDisposed()) {
    
    
                try {
    
    
                    observer.onError(t);
                } finally {
    
    
                    dispose();
                }
            } else {
    
    
                RxJavaPlugins.onError(t);
            }
        }

        @Override
        public void onComplete() {
    
    
            if (!isDisposed()) {
    
    
                try {
    
    
                    observer.onComplete();
                } finally {
    
    
                    dispose();
                }
            }
        }

ObservableCreate inherits from Observable, where the source is the ObservableOnSubscribe mentioned above, which is the parameter passed in by the Create() method:

 Observable.create(new ObservableOnSubscribe<Integer>() {
    
    

            @Override
            public void subscribe(ObservableEmitter<Integer> e) throws Exception {
    
    
                e.onNext(123);
            }
        })

Let's focus on the subscribeActual() method:

@Override
protected void subscribeActual(Observer<? super T> observer) {
    
    
    CreateEmitter<T> parent = new CreateEmitter<T>(observer);
    observer.onSubscribe(parent);

    try {
    
    
        source.subscribe(parent);
    } catch (Throwable ex) {
    
    
        Exceptions.throwIfFatal(ex);
        parent.onError(ex);
    }
}

Here, an observer is passed as a parameter to the internal class of CreateEmitter again. Let's follow the code to see what the internal class of CreateEmitter does:

 static final class CreateEmitter<T>
    extends AtomicReference<Disposable>
    implements ObservableEmitter<T>, Disposable {
    
    


        private static final long serialVersionUID = -3434801548987643227L;

        final Observer<? super T> observer;

        CreateEmitter(Observer<? super T> observer) {
    
    
            this.observer = observer;
        }

        @Override
        public void onNext(T t) {
    
    
            if (t == null) {
    
    
                onError(new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources."));
                return;
            }
            if (!isDisposed()) {
    
    
                observer.onNext(t);
            }
        }

        @Override
        public void onError(Throwable t) {
    
    
            if (t == null) {
    
    
                t = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources.");
            }
            if (!isDisposed()) {
    
    
                try {
    
    
                    observer.onError(t);
                } finally {
    
    
                    dispose();
                }
            } else {
    
    
                RxJavaPlugins.onError(t);
            }
        }

        @Override
        public void onComplete() {
    
    
            if (!isDisposed()) {
    
    
                try {
    
    
                    observer.onComplete();
                } finally {
    
    
                    dispose();
                }
            }
        }

I believe that by now, everyone can basically understand it. Yes, this is where we enter the event. Here, according to the incoming observer parameters, for example, the onNext() method is called, and the onNext() method of the Observer is also called at the same time. Play the effect of event monitoring. At the same time, CreateEmitter implements Disposable. As long as this class plays the role of interrupting event delivery, the boolean value of isDisposed() is used to determine whether to continue to distribute the monitoring event or to call onComplete() to end the event. At the same time, it also guarantees onComplete () and onError() cannot be called at the same time. We then look down at the code:

 source.subscribe(parent);

This takes CreateEmitter as a parameter and calls the subscribe method in ObservableOnSubscribe, which is executed here:
Observable.create(new ObservableOnSubscribe() {​
In summary, it can be said that the subscribeActual() method plays a role in connecting the above and the next, and is the core of Rxjava! So where is this method called? We continue to follow the source code analysis:

Insert picture description here
Here the subscribe() method of Observerable is called:

 @SchedulerSupport(SchedulerSupport.NONE)
    @Override
    public final void subscribe(Observer<? super T> observer) {
    
    }
        try {
    
    
            observer = RxJavaPlugins.onSubscribe(this, observer);
            subscribeActual(observer);
            }
......
    }

The observer object is passed in here, and oberver's onSubscribe() method is called at the same time. This is why onSubscribe() is called for the first time, and then our most important subscribeActual(observer) method is called. It can be known that in the entire Rxjava call chain, only when the subscribe (subscription) occurs, the event will be monitored and distributed!

Guess you like

Origin blog.csdn.net/qq_39431405/article/details/112788436