RxJava Operator Learning Memorandum

Keywords: Java

Operator learning

  1. create: The most basic method for creating Observable, which is used by Observable Emitter to send events and can cut off subscription relationships upstream and downstream
  Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> e) throws Exception {
              if (!e.isDisposed()) {
                    e.onNext(1);
                    e.onNext(2);
                    e.onNext(3);
                    e.onComplete();
                }
            }
        })

2.just: Create an Observable object that sends events in turn

3.Map: Used to wrap transformation events

   observable.map(new Function<Integer, String>() {
                    @Override
                    public String apply(Integer integer) throws Exception {
                        Log.i(TAG, "apply Thread:" + Thread.currentThread().getName());
                        return "soilder" + integer;
                    }
                })

4.FlatMap: Used to split events into multiple events for sending, but not to ensure the sequence of events

observable. .flatMap(new Function<Integer, ObservableSource<String>>() {
                    @Override
                    public ObservableSource<String> apply(Integer integer) throws Exception {
                        Log.i(TAG, "apply Thread:" + Thread.currentThread().getName());
                        ArrayList<String> arrayList = new ArrayList<String>();
                        for (int i = 0; i < 3; i++) {
                            String s = "to be Number" + integer;
                            arrayList.add(s);
                        }
                        return Observable.fromIterable(arrayList).delay(1000, TimeUnit.MILLISECONDS);//By delaying, you can see that it's out of order.
                    }
                })

5. ConatMap is similar to flatMap, but it ensures that events are sent in strict order.
6.switchMap is similar to concatMap in that it guarantees the sequence of events. The difference is that if the data source Observable produces three results: A, B and C, through the custom mapping rules of switchMap, A1, A2, B1, B2, C1 and C2 should be generated after mapping. However, while B2 is produced, C1 has been produced, so the final result becomes A1, A2, B1, C1, C2, B2 is discarded.

7.zip Composite Event Combines Two Event Sources into One Event Source

 Observable<Integer> observable1 = Observable.range(1, 3).subscribeOn(Schedulers.io());

        Observable<String> observable2 = Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                debugLog("subscribe Thread:" + Thread.currentThread());
                e.onNext("Student");
                e.onNext("Student");
                e.onNext("Student");
                e.onNext("Student");
                e.onComplete();
            }
        }).subscribeOn(Schedulers.newThread());

        Observable.zip(observable1, observable2, new BiFunction<Integer, String, String>() {

            @Override
            public String apply(Integer integer, String s) throws Exception {
                return s + integer;
            }
        })

8.buffer(int size,int skip), set the buffer length to start, skip skip each time

Observable.just("one", "two", "three", "four", "five").buffer(3, 2).subscribe(new Observer<List<String>>() {

            @Override
            public void onSubscribe(Disposable d) {
                Log.d(TAG, " onSubscribe : " + d.isDisposed());
            }

            @Override
            public void onNext(List<String> stringList) {
                debugLog(" onNext size : " + stringList.size());
                Log.d(TAG, " onNext : size :" + stringList.size());
                for (String value : stringList) {
                    debugLog(" value : " + value);
                }

            }

            @Override
            public void onError(Throwable e) {
                debugLog(" onError : " + e.getMessage());
            }

            @Override
            public void onComplete() {
                debugLog(" onComplete");
            }
        });
 //The result of printing is"one", "two", "three"
 //"three", "four", "five"
 //"five"

9.Completable observer class, which can only send observers who complete events

Completable.create(new CompletableOnSubscribe() {
            @Override
            public void subscribe(CompletableEmitter e) throws Exception {
                e.onComplete();
            }
        }).subscribe(new CompletableObserver() {
            @Override
            public void onSubscribe(Disposable d) {
                debugLog(" onSubscribe ");
            }

            @Override
            public void onComplete() {
                debugLog(" onComplete ");
            }

            @Override
            public void onError(Throwable e) {
                debugLog(" onError ");
            }
        });

10.filter filtering, used to filter events that are not needed for tuning

11. Deounce handles events downstream whenever no new event occurs in a certain event segment after each result is produced. If there are new events, it handles new events downstream. Timing starting point is reset to the starting point of the sent event. (This method remembers that the starting point is the time point of the event's sending.)
It's very useful when manipulating instant search boxes

 Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> e) throws Exception {
                // send events with simulated time wait
                e.onNext(1); // skip
                Thread.sleep(400);
                e.onNext(2); // deliver
                Thread.sleep(505);
                e.onNext(3); // skip
                Thread.sleep(100);
                e.onNext(4); // deliver
                Thread.sleep(605);
                e.onNext(5); // deliver
                Thread.sleep(510);
                e.onComplete();
            }
        }).debounce(500, TimeUnit.MILLISECONDS)
                .observeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Integer>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        debugLog(" onSubscribe ");
                    }

                    @Override
                    public void onNext(Integer value) {
                        debugLog(" onNext ");
                        debugLog(" value: " + value);
                    }

                    @Override
                    public void onError(Throwable e) {
                        debugLog(" onError ");
                    }

                    @Override
                    public void onComplete() {
                        debugLog(" onComplete ");
                    }
                });

12. The defer operator actually works the same as the create operator. Of course, the Create method requires you to manually send onComplete events. The defer is different from just, front and other operators, which store event objects when creating the observed object. The content of the event at the time of sending determines the content of the event so that the latest event object can be obtained, just for the event of object type. The same as defer effect is the problem of designing deep and shallow copies of java

13. Composite Disposable and subscribeWith.subscribeWith are used to return Disposable objects, Composite Disposable is used to store Disposable objects, and Composite Disposable objects cut off the relationship between all observers and observers by calling clear method.

14.distinct method for eliminating duplicate events

15. Reduc method is used for the functions of cumulative subtraction, cumulative multiplication and so on.

16. Functional interval (long initial Delay, long period, TimeUnit unit) similar to timer

17. Last (T) Sends a default event when the upstream does not send an event

18.merge integrates two data sources into one without changing the order in which events are sent.

19.lift() operator, a high-order low-level operator, can try to use lift when the existing operators can not meet the needs, which uses the proxy mode to achieve, but generally not recommended to use, prone to unexpected errors. Generally try to use commonly used operation symbols.

20.compose is used to transform Observable. When a group of Observables is transformed by a series of flat,Map needs to use Compose.

 Observable observable1=Observable.just(1,2,3).map(integer -> integer+"A")
                .delay(100,TimeUnit.MILLISECONDS)
                .filter(s -> s.contains("1"));

Observable observable2=Observable.just(9,12,14).map(integer -> integer+"A")
                .delay(100,TimeUnit.MILLISECONDS)
                .filter(s -> s.contains("1"));

Observable observable3=Observable.just(8,5,14).map(integer -> integer+"A")
                .delay(100,TimeUnit.MILLISECONDS)
                .filter(s -> s.contains("1"));

.......

Of course it can be written as follows:

   public void PretreatmentObservable(Observable<Integer> ob){
        ob.map(integer -> integer+"A")
                .delay(100,TimeUnit.MILLISECONDS)
                .filter(s -> s.contains("1"));;
    }
PretreatmentObservable(Observable.just(1,2,3))
PretreatmentObservable(Observable.just(9,12,14))
PretreatmentObservable(Observable.just(8,5,14)) 

.......

compose() can be used to maintain chain operations

ObservableTransformer<Integer,String>  transform=new ObservableTransformer<Integer, String>(){
            @Override
            public ObservableSource apply(Observable<Integer> upstream) {
                return upstream.map(new Function<Integer,String>() {
                    @Override
                    public String apply(Integer i ) throws Exception {
                        return i+"A";
                    }
                }).filter(new Predicate<String>() {
                    @Override
                    public boolean test(String s) throws Exception {
                        return s.contains("1");
                    }
                }).delay(100,TimeUnit.MILLISECONDS);
            }
};

        Observable.just(1,2,3).compose(transform);
        Observable.just(9,12,14).compose(transform);
        Observable.just((8,5,14).compose(transform);
.......

Posted by Molarmite on Thu, 27 Jun 2019 14:40:52 -0700