RxJava2 learning tutorial (1) hello world

hi, long time no see.
emem, yes, it seems that it has been a long time since I have n’t updated my blog. I have never had the habit of blogging on CSDN. I input and output myself, and lack of continuous thinking and memory. In the future learning process, I will continue to organize and share what I have learned and some thoughts. Everyone learns together and continuously improves.

-------------------------------------------------- --------------- officially opened the following -------------------------------- -----------------------------

RxJava2 learning tutorial (1) hello world

The content we are learning today is RxJava. Those who have used AsyncTask before must be familiar with asynchronous. RxJava is a popular asynchronous framework in Android. Next, we will start the learning journey of learning Rxjava.
This is the first article about RxJava. Today I will mainly introduce the use and basic knowledge of RxJava2.

  • Use: How to transmit and receive events
  • Basic knowledge: principles and important APIs

1. About RxJava

  • RxJava is a Java implementation of Reactive Extensions, used to build libraries of asynchronous and event-based programs by using Observable / Flowable sequences.
  • RxJava extends the observer pattern to support data / event sequences, and adds operators that allow you to combine sequences in a declarative manner, while extracting hiding from low-priority threads, synchronization, thread safety, and concurrent data structures.
  • For RxJava, the application is very wide, anywhere, including the underlying framework that App depends on, for AsyncTask in Android, RxJava can also be used instead. Of course, not only the development of Android APP, but also often used in the field of server side RxJava. Today we will walk into the learning journey of RxJava together.

2. Use of RxJava

2.1 Add configuration

We want to use RxJava2 in Android, first add the following configuration in the app's build.gradle file:

// Rxjava
    implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
    implementation 'io.reactivex.rxjava2:rxjava:2.2.9'
2.2 Hello world in RxJava2

Principle introduction: RxJava is based on the observer pattern, through which the observer transmits data and the observer receives data. Here we use two water pipes to replace the observer and the observer. Call it downstream.

  • Create Observable (upstream)

Observable It determines when to trigger the event, where you can determine the order and number of asynchronous operation modules.

  • Create Observer (downstream)

Observer can perform tasks in different threads. It is an observer sentry in standby state, which is used to respond to Observable notifications at a certain time, without waiting for Observable to transmit data without blocking.

  • Subscribe with subscribe ()

The subscribe () method is used to connect the Observable and Observer created previously, so that the entire upstream and downstream can be connected to realize chained calls.

The specific implementation code is as follows:

// 创建Observable
Observable<String> mObservable =Observable.create(new ObservableOnSubscribe<String>() {
                    @Override
                    public void subscribe(ObservableEmitter<String> emitter) {
                        emitter.onNext("hello world");
                    }
                });
// 创建 observer
  Observer<String> mObserver=new Observer<String>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(String s) {
               
                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            };
 // subscribe() 调用
  mObservable.subscribe(mObserver);
  • The simplified version is as follows:
  Observable.just("hello world").subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        Log.d(TAG, "accept: "+s);
                    }
                });
  • Chained calls (we often use chained calls in development)
  Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
                Log.d(TAG, "onNext:我方已成功发送 "+1);
                emitter.onNext(1);
                Log.d(TAG, "onNext:我方已成功发送 "+2);
                emitter.onNext(2);
                Log.d(TAG, "onNext:我方已成功发送 "+3);
                emitter.onNext(3);
                Log.d(TAG, "onNext:我方已成功发送 "+4);
                emitter.onNext(4);
                Log.d(TAG, "onNext:我方已成功发送 "+5);
                emitter.onNext(5);
                Log.d(TAG, "发送完毕! ");
                emitter.onComplete();
            }
        }).map(new Function<Integer, String>() {
            @Override
            public String apply(Integer integer) throws Exception {
                return "我方已成功接收:"+integer;
            }
        }).subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }
            @Override
            public void onNext(String s) {
                Log.d(TAG, "onNext: "+s);
                Log.d(TAG, "........................... ");
            }
            @Override
            public void onError(Throwable e) {

            }
            @Override
            public void onComplete() {
                Log.d(TAG, "接收完毕! ");
                Log.d(TAG, "........................... ");
            }
        });

The results of the program run are as follows:
Insert picture description here

The above code is very simple, then we mainly explain the technical points and important APIs.

(1) ObservableEmitter:

It can be understood as a transmitter. It can be used to launch events. It can emit three types of events onNext(T value), onComplete()and the onError(Throwable error)next event, complete event, and error event can be issued by calling emitter , and .

  • Launch rules:

    • Upstream can send unlimited onNext, downstream can also receive unlimited onNext.
    • When the upstream sends an onComplete, the event after the upstream onComplete will be 继续sent, and the downstream will 不再继续receive the event after receiving the onComplete event.
    • When the upstream sends an onError, the event after the upstream onError will be 继续sent, and the downstream will 不再继续receive the event after receiving the onError event. The upstream may not send onComplete or onError.
    • onComplete and onError must be unique and mutually exclusive, that is, you cannot send multiple onComplete, you cannot send multiple onError, you can not send an onComplete first, and then send an onError, and vice versa
  • The calling sequence of events:

    onSubscribe->onNext->onComplete
    
(2)Disposable:

Its Chinese meaning is one-time and freely disposable. In RxJava, we can understand it as a hub or data switch that controls the data transmission between the upstream observable and the downstream observer. We can call Disposable dispose at a certain time. () Close, so that the upstream can continue to emit events, but the downstream will no longer receive events once dispose () is triggered.

The sample code is as follows:

Observable<String> mObservable =Observable.create(new ObservableOnSubscribe<String>() {
                    @Override
                    public void subscribe(ObservableEmitter<String> emitter) {
                        emitter.onNext("kotlin");
                        Log.d(TAG, "subscribe:kotlin ");
                        emitter.onNext("Java");
                        Log.d(TAG, "subscribe: Java");
                        emitter.onNext("C++");
                        Log.d(TAG, "subscribe: C++");
                        emitter.onNext("Python");
                        Log.d(TAG, "subscribe: Python");
                        emitter.onNext("go");
                        Log.d(TAG, "subscribe: go");
                    }
                });

                Observer<String> mObserver=new Observer<String>() {

                    private Disposable mDisposable;
                    private int i;
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable = d;
                    }

                    @Override
                    public void onNext(String s) {
                        Log.d(TAG, "onNext: "+s);
                           i++;
                           if (i==2){
                               mDisposable.dispose();
                               Log.d(TAG, "onNext: 下游已关闭,将不再接收任何数据");
                           }


                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                };

                mObservable.subscribeOn(Schedulers.newThread())      //上游线程
                        .observeOn(AndroidSchedulers.mainThread())   // 下游线程
                        .subscribe(mObserver);

The results are as follows:

11-27 01:41:19.692 30223-30293/com.example.dolphkon.hellokotlin D/HelloRxjavaActivity:       subscribe:kotlin 
    subscribe: Java
    subscribe: C++
    subscribe: Python
    subscribe: go
11-27 01:41:19.693 30223-30223/com.example.dolphkon.hellokotlin D/HelloRxjavaActivity:       onNext: kotlin
    onNext: Java
    onNext: 下游已关闭,将不再接收任何数据

We can see two points from the above code:

  • Disposable does not affect the upstream to continue the launch event
  • When Disposabl.dispose () is triggered, the downstream will no longer continue to receive events
(3) Overload method of subscribe ()
    public final Disposable subscribe() {}
    public final Disposable 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 subscribe(Observer<? super T> observer) {}
  • Without any parameters, it subscribe()means that the downstream does not care about any events, you can send your data upstream.
  • ConsumerThe method with a parameter means that the downstream only cares about the onNext event, and I pretend not to see other events, so if we only need the onNext event, we can write this
        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
                Log.d(TAG, "emit 1");
                emitter.onNext(1);
                Log.d(TAG, "emit 2");
                emitter.onNext(2);
                Log.d(TAG, "emit 3");
                emitter.onNext(3);
                Log.d(TAG, "emit complete");
                emitter.onComplete();
                Log.d(TAG, "emit 4");
                emitter.onNext(4);
            }
        }).subscribe(new Consumer<Integer>() {
            @Override
            public void accept(Integer integer) throws Exception {
                Log.d(TAG, "onNext: " + integer);
            }
        });

Well, about the use of RxJava2, we will temporarily introduce it here today. The next article will introduce the scheduling of threads in RxJava2.

Released eight original articles · won praise 9 · views 6198

Guess you like

Origin blog.csdn.net/DolphKong/article/details/105687706