RxJava operator application
Import and stock in:
api("io.reactivex.rxjava3:rxjava:3.1.0") api('io.reactivex.rxjava3:rxandroid:3.1.0')
Operator classification
Create Operator Complex data traversal just fromArray fromIterable range Timed task interval intervalRange Nested callback asynchronous events create Delayed task defer timer Transform operator Transformation map flatMap concatMap Merge operator Combine multiple observers and merge events concatArray(Send event--serial ) concatDelayError megerArray(Send event--parallel) megerArrayDelayError Combine multiple observers and merge them into one observer zip combineLatest Append other events before sending events startWithArray Combine multiple events into one event reduce collect Summarize the number of events sent count Filter operator Specify filter conditions to filter the required events/data filter Filter events of the specified type/data ofType Events with unsatisfied filter conditions/data skip Filter out duplicate events/data distinct distinctUntilChanged Filter events by time or quantity/data take Filter events at the specified location elementAt Filter events by event segment throttleFirst throttleLast Conditional Operator Judge whether all events meet all When the sent event judgment conditions are not met, the subsequent event reception will be terminated takeWhile Subsequent events are received only when the judgment conditions of the sent event are not met skipWhile Filter events(with filter) takeUntil Receive events other than determining that the conditions are met skipUntil Judge whether the events of the two observers are the same sequenceEqual Judge whether the sent data contains the specified data contains Judge whether the sent data is empty isEmpty Multiple observers, only receive"The first observer to successfully send data" amb Other function operators frequently-used do Series operator doOnEach doOnSubscribe doOnNext doAfterNext doOnComplete doOnErro error/exception handling Catch exceptions and feed back special results&Normal termination onErrorRetuturn Catch the exception and return a new event onErrorResumeNext Exception retry retry Event retransmission repeat repeatWhen repeatUntil Delay sending the observed event delay Send event timeout processing timeout
1, Create operator
1. **just** Converts one or more objects into one that emits this or these objects Observable 2. **from** Will one Iterable,Future Or convert an array into an array Observable 3. **create** Use a function to create one from scratch Observable 4. **defer** A subscription is created only when the subscriber subscribes Observable,Create a new subscription for each subscription Observable 5. **range** Creates a sequence that emits a specified range of integers Observable 6. **interval** Creates a sequence of integers sent at a given time interval Observable 7. **timer** Creates a method for transmitting single data after a specified delay Observable 8. **empty** Create one that is done without direct notification Observable 9. **error** Create one that does nothing to directly notify errors Observable 10. **never** No data is transmitted
1.create
There are two kinds of subscribe callbacks: one is the Observer callback back to all methods, and the other is the Consumer, which can call back the methods you need
Observable.create(new ObservableOnSubscribe<String>() { @Override public void subscribe(@NonNull ObservableEmitter<String> emitter) throws Throwable { emitter.onNext("hahahhahhh"); int a = 0; int b = 11/a; //Throw an exception and call back to the onError method } }).subscribe(new Observer<String>() { @Override public void onSubscribe(@NonNull Disposable d) { } @Override public void onNext(@NonNull String s) { System.out.println(s); } @Override public void onError(@NonNull Throwable e) { System.out.println(e.getMessage()); } @Override public void onComplete() { } }); Observable.create(new ObservableOnSubscribe<String>() { @Override public void subscribe(@NonNull ObservableEmitter<String> emitter) throws Throwable { emitter.onNext("hahahhahhh"); int a = 0; int b = 11/a; //Throw an exception and call back to the onError method } }).subscribe(new Consumer<String>() { @Override public void accept(String s) throws Throwable { System.out.println(s); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Throwable { System.out.println("I'm abnormal"+throwable.getMessage()); } });
2.just and from
just operator: convert an object into an Observable object and emit it. It can make a number, a string, an array, an Iterate object, etc. it is a very fast method to create an Observable object~
Observable.just(mList).subscribe(new Observer<List<String>>() { @Override public void onSubscribe(@NonNull Disposable d) { } @Override public void onNext(@NonNull List<String> strings) { System.out.println(strings); } @Override public void onError(@NonNull Throwable e) { } @Override public void onComplete() { } }); Observable.just(1,2,3,4,5).subscribe(new Consumer<Integer>() { @Override public void accept(Integer integer) throws Throwable { System.out.println(integer); } });
From operator: used to convert an object into an Observable object and emit its contents in turn. The received value of from can be a set or array, which is similar to just, but just will emit the whole object. For example, for a set containing three elements, from will divide the set into three launches, while just will launch once to launch the whole array~
Observable.fromArray(mList).subscribe(new Consumer<List<String>>() { @Override public void accept(List<String> strings) throws Throwable { System.out.println(strings); } });
3.defer operator
The Defer operator creates a new Observable object only when there is a Subscriber to subscribe, that is, each subscription will get the latest Observable object just created, which can ensure that the data in the Observable object is up-to-date, while just does not create a new Observable object
Consumer<String> action1 = new Consumer<String>() { @Override public void accept(String s) throws Throwable { System.out.println(s); } }; // defer Observable<String> defer = Observable.defer(new Supplier<ObservableSource<? extends String>>() { @Override public ObservableSource<? extends String> get() throws Throwable { Object o = new Object(); return Observable.just("defer : hashCode = " + o.hashCode()); } }); defer.subscribe(action1); defer.subscribe(action1); defer.subscribe(action1); // just Observable<String> just = Observable.just("just : hashCode = " + new Object().hashCode()); just.subscribe(action1); just.subscribe(action1); just.subscribe(action1);
Print:
defer : hashCode = 1865127310 defer : hashCode = 292938459 defer : hashCode = 917142466 just : hashCode = 1993134103 just : hashCode = 1993134103 just : hashCode = 1993134103
It can be seen from the output results that defer subscribed three times, but the address value changed each time, while just has the same address value three times, thus verifying the above conclusion.
4.range operator
The Range operator emits a value greater than or equal to start for count times according to the input initial value [start] and quantity [count]~
Observable.range(100,10).subscribe(new Observer<Integer>() { @Override public void onSubscribe(@NonNull Disposable d) { } @Override public void onNext(@NonNull Integer integer) { System.out.println(integer); } @Override public void onError(@NonNull Throwable e) { } @Override public void onComplete() { System.out.println("onComplete"); } });
Print results:
100 101 102 103 104 105 106 107 108 109 onComplete Process finished with exit code 0
5.interval operator
The Observable object created by Interval starts from 0 and emits a number every fixed time. It should be noted that this object runs in the computing scheduler and needs to run in the Android project. Therefore, to update the UI, you need to subscribe in the main thread ~. In the project, it can be used as a timer
Observable.interval(1, TimeUnit.SECONDS) .subscribeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<Long>() { @Override public void accept(Long aLong) throws Throwable { Log.e("---->","time "+aLong); } });
6.timer operator
Timer will emit a number 0 after the specified time. Note that it also runs in the calculation scheduler ~, similar to postdelay
Log.e("---->","count down "+10 +"Execute in seconds"); Observable.timer(10,TimeUnit.SECONDS).subscribe(new Consumer<Long>() { @Override public void accept(Long aLong) throws Throwable { Log.e("---->","Start execution"); } });
7.empty operator
Create an empty Observable that will not emit any events (data)
Observable<String> empty = Observable.empty(); empty.subscribe(new Observer<String>() { @Override public void onSubscribe(@NonNull Disposable d) { System.out.println("onSubscribe : "+d); } @Override public void onNext(@NonNull String s) { System.out.println("onNext: "+s); } @Override public void onError(@NonNull Throwable e) { System.out.println("onError :"+e.getMessage()); } @Override public void onComplete() { System.out.println("onComplete"); } });
8.never operator
Create an Observable without transmitting any data or sending any notification to the Observer subscribing to ta~
Unlike empty, never does not perform onComplete
Observable<String> never = Observable.never(); never.subscribe(new Observer<String>() { @Override public void onSubscribe(@NonNull Disposable d) { System.out.println("onSubscribe : "+d); } @Override public void onNext(@NonNull String s) { System.out.println("onNext: "+s); } @Override public void onError(@NonNull Throwable e) { System.out.println("onError :"+e.getMessage()); } @Override public void onComplete() { System.out.println("onComplete"); } });
9.error operator
Returns an Observable. When an Observer subscribes to ta, call the onError method of the Observer directly to terminate
Observable<String> error = Observable.error(new Throwable("Observable error")); error.subscribe(new Observer<String>() { @Override public void onSubscribe(@NonNull Disposable d) { System.out.println("onSubscribe : "+d); } @Override public void onNext(@NonNull String s) { System.out.println("onNext: "+s); } @Override public void onError(@NonNull Throwable e) { System.out.println("onError :"+e.getMessage()); } @Override public void onComplete() { System.out.println("onComplete"); } });
10.repeat operator
Repeat will repeatedly transmit an Observable object. The received value is the number of times it is transmitted, and it is still subscribed to the calculation scheduler~
Observable.just(1,2).repeat(10).subscribe(new Consumer<Integer>() { @Override public void accept(Integer integer) throws Throwable { System.out.println("accept : "+integer); } });
11.delay operator
The function is the same as that of the timer operator, but delay is used in events to delay the sending of a certain event~
Must be implemented in the Android project:
Observable.just(1,2).delay(2, TimeUnit.SECONDS).subscribe(new Consumer<Integer>() { @Override public void accept(Integer integer) throws Throwable { Log.e("---->","Start execution" +integer); } });
2, Transform operator
**> Map
FlatMap
GroupBy
GroupBy
Buffer
Scan
Window...**
1.Map operator
Mapping is generally used to process the original data and return the processed data~
Observable.create(new ObservableOnSubscribe<String>() { @Override public void subscribe(@NonNull ObservableEmitter<String> emitter) throws Throwable { emitter.onNext("https://www.baidu.com"); } }).map(new Function<String, URL>() { @Override public URL apply(String s) throws Throwable { return new URL(s); } }).subscribe(new Consumer<URL>() { @Override public void accept(URL url) throws Throwable { System.out.println(url); } });
2.FlatMap operator
Flat mapping is used to change the data transmitted by an original Observable, output one or more observables, and then flatten the data transmitted by these observables into a separate Observable (the parameter is generally Function)~
Observable.just("register").flatMap(new Function<String, ObservableSource<?>>() { @Override public ObservableSource<String> apply(String s) throws Throwable { System.out.println(s); System.out.println("login was successful"); return Observable.just("Request login"); } }).subscribe(new Observer<Object>() { @Override public void onSubscribe(@NonNull Disposable d) { } @Override public void onNext(@NonNull Object o) { System.out.println(o); System.out.println("Login succeeded " ); } @Override public void onError(@NonNull Throwable e) { } @Override public void onComplete() { } });
3.concatMap operator
The function of the concatMap operator is very similar to that of flatMap, except that * * the final output data sequence of concatMap is consistent with the original data sequence. It links Observables in order rather than merging (flatMap uses merging).
Let's take an example: * * Observable transmits 5 data (1, 2, 3, 4, 5), and then respectively
Perform a transformation (* 10) on it with flatMap and concatMap, and then output the result sequence.
Observable.fromArray(1,2,3,4,5) .concatMap(new Function<Integer, ObservableSource<Integer>>() { @Override public ObservableSource<Integer> apply(Integer integer) throws Throwable { int delay = 0; if(integer == 3){ delay = 500;//Delay 500ms launch } return Observable.just(integer *10).delay(delay, TimeUnit.SECONDS); } }).subscribe(new Consumer<Integer>() { @Override public void accept(Integer integer) throws Throwable { Log.e("---->","concatMap :"+integer); } }); Observable.fromArray(1,2,3,4,5) .flatMap(new Function<Integer, ObservableSource<Integer>>() { @Override public ObservableSource<Integer> apply(Integer integer) throws Throwable { int delay = 0; if(integer == 3){ delay = 500;//Delay 500ms launch } return Observable.just(integer *10).delay(delay, TimeUnit.SECONDS); } }).subscribe(new Consumer<Integer>() { @Override public void accept(Integer integer) throws Throwable { Log.e("---->","flatMap :"+integer); } });
It is concluded that concatMap will print sequentially, and flatMap printing is disordered
4.Buffer operator
It can be simply understood as cache, which can collect data from Observable in batch or periodically to a set, and then package and transmit these data sets, rather than transmitting one data at a time~
Observable.range(0,10) .buffer(3) .subscribe(new Consumer<List<Integer>>() { @Override public void accept(List<Integer> integers) throws Throwable { System.out.println(integers); } });
5.GroupBy operator
Group filtering
Observable.range(0,10) .groupBy(new Function<Integer, Integer>() { @Override public Integer apply(Integer integer) throws Throwable { return integer/2; } }).subscribe(new Consumer<GroupedObservable<Integer, Integer>>() { @Override public void accept(GroupedObservable<Integer, Integer> integerIntegerGroupedObservable) throws Throwable { System.out.println(integerIntegerGroupedObservable.getKey()); } });
6.Sacn operator
sacn operator is the result generated by traversing the source Observable, and outputs the result to the subscriber in turn through custom conversion rules,
Observable.range(0,5) // The first parameter is the last settlement result, // The second parameter is the input value of observable for this source .scan(new BiFunction<Integer, Integer, Integer>() { @Override public Integer apply(Integer integer, Integer integer2) throws Throwable { return integer+integer2; } }).subscribe(new Consumer<Integer>() { @Override public void accept(Integer integer) throws Throwable { System.out.println(integer); } });
7.Window operator
You can collect data from Observable in batches or periodically into a set, and then package and transmit these data sets instead of transmitting one data at a time, similar to Buffer, but Buffer transmits data and Window transmits Observable~
Observable.range(0,5) .window(2) .subscribe(new Consumer<Observable<Integer>>() { @Override public void accept(Observable<Integer> integerObservable) throws Throwable { System.out.println("onOutsideNext -->" + integerObservable); integerObservable.subscribe(new Consumer<Integer>() { @Override public void accept(Integer integer) throws Throwable { System.out.println(integer); } }); } });
3, Merge operator
1.merge(), concat() operator
The merge operator combines multiple observables into one for emission. Merge may cause disorder in the order of data merged into Observable (combined number of observers < = 4) (parallel disorder)
The mergeArray operator works the same as merge, but the difference is that the number of observers is > 4 (parallel and unordered)
Observable observable1 = Observable.just(1, 2, 3); Observable observable2 = Observable.just("Apple", "Banana", "a mandarin orange"); Observable.merge(observable1,observable2) .subscribe(new Consumer() { @Override public void accept(Object o) throws Throwable { System.out.println("merge:"+ o.toString()); } });
The concat operator also combines multiple observables into one for emission. However, concat ensures that the combined Observable events are emitted in sequence. (number of combined observers < = 4) (serial order)
The concatArray operator has the same function as concat, but the difference is that the number of combined observers is > 4) (serial order)
Observable observable1 = Observable.just(1, 2, 3); Observable observable2 = Observable.just("Apple", "Banana", "a mandarin orange"); Observable observable3 = Observable.just(false,true); Observable.concat(observable1,observable2,observable3) .subscribe(new Consumer() { @Override public void accept(Object o) throws Throwable { System.out.println("concat:"+ o.toString()); } });
2.concatArrayDelayError()/mergeArrayDelayError() operator
The purpose of these two operators is: when using concat() and merge() operators, if one of the observers sends an onError event, it will immediately terminate the other observers to continue sending events. Therefore, using the concatError()/mergeDelayError() event at this time can delay the onError event until other observers send the event
Observable .concatArrayDelayError(Observable.create(new ObservableOnSubscribe<Integer>() { @Override public void subscribe(ObservableEmitter<Integer> emitter) throws Exception { emitter.onNext(1); emitter.onNext(2); emitter.onError(new NullPointerException()); emitter.onNext(3); emitter.onNext(4); } }), Observable.just(5, 6)) .subscribe(new Observer<Integer>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(Integer integer) { System.out.println( "Received message "+String.valueOf(integer)); } @Override public void onError(Throwable e) { System.out.println("cDelayError"+ "onError"); System.out.println(e.getMessage()); } @Override public void onComplete() { System.out.println( "onComplete"); } });
As like as two peas, the same output.
Observable .mergeArrayDelayError(Observable.create(new ObservableOnSubscribe<Integer>() { @Override public void subscribe(ObservableEmitter<Integer> emitter) throws Exception { emitter.onNext(1); emitter.onNext(2); emitter.onError(new NullPointerException()); emitter.onNext(3); emitter.onNext(4); } }), Observable.just(5, 6)) .subscribe(new Observer<Integer>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(Integer integer) { System.out.println( "Received message "+String.valueOf(integer)); } @Override public void onError(Throwable e) { System.out.println("cDelayError"+ "onError"); System.out.println(e.getMessage()); } @Override public void onComplete() { System.out.println( "onComplete"); } });
3.zip operator
After merging multiple observables, the data of these observables are converted and then transmitted. The number of converted data is determined by the Observable with the shortest data length. After the launch, the observer's onComplete method () will be called automatically
Observable observable1 = Observable.just(1, 2, 3); Observable observable2 = Observable.just("Apple", "Banana", "a mandarin orange"); Observable observable3 = Observable.just(false,true); Observable.zip(observable1, observable2, observable3, new Function3<Integer, String, Boolean, String>() { @Override public String apply(Integer integer, String s, Boolean aBoolean) throws Throwable { return integer +s +aBoolean; } }). subscribe(new Observer() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(Object o) { System.out.println( "onNext: "+ o.toString()); } @Override public void onError(Throwable e) { } @Override public void onComplete() { System.out.println( "onComplete"); } });
4.combineLatest operator
When either of the two observables sends data, the latest (last) data of the Observable that sent the data first is combined with each data sent by the other Observable, and finally the data is sent based on the result of the combination. The difference between zip() and zip(): zip() is combined by number, that is, 1-to-1; combineLatest() is a time-based merge, that is, merge at the same time point
Observable.combineLatest(Observable.just(1, 2, 3), Observable.intervalRange(3, 5, 2, 1, TimeUnit.SECONDS), new BiFunction<Integer, Long, String>() { @Override public String apply(Integer integer, Long aLong) throws Throwable { return "The consolidated data are:" + integer + aLong; } }).subscribe(new Observer<String>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(String s) { Log.e("---->","combineLatest:"+ s); } @Override public void onError(Throwable e) { } @Override public void onComplete() { Log.e("---->","onComplete"); } });
5.reduce operator
Aggregate the data to be sent by the observer into a data transmission according to the specified rules
Aggregation rules need to be written by us. The internal process is to merge the first two data according to our rules, then merge with the following data according to rules, and so on (classes use data accumulation and merging for operation, and the rules are specified by themselves).
Observable.just(1,2,3,4,5,6) .reduce(new BiFunction<Integer, Integer, Integer>() { @Override public Integer apply(Integer integer, Integer integer2) throws Throwable { return integer+integer2; } }).subscribe(new Consumer<Integer>() { @Override public void accept(Integer integer) throws Throwable { System.out.println(integer); } });
6.collect operator
The function is to collect the events sent by the observable into a data structure
Observable .just(1, 2, 3, 4, 5).collect(new Supplier<ArrayList<Integer>>() { @Override public ArrayList<Integer> get() throws Throwable { return new ArrayList<>(); } }, new BiConsumer<ArrayList<Integer>, Integer>() { @Override public void accept(ArrayList<Integer> integers, Integer integer) throws Throwable { integers.add(integer); } }).subscribe(new Consumer<ArrayList<Integer>>() { @Override public void accept(ArrayList<Integer> integers) throws Throwable { Log.e("---->",""+integers); } });
7.startWith/startWithArray operator
Before the sending time of an observer, send some additional data / a new observer
Observable.just(1,2,3) .startWithArray(5,6) .startWith(Observable.just(1,2,3)) .subscribe(new Consumer<Integer>() { @Override public void accept(Integer integer) throws Throwable { System.out.println(integer); } });
8. Count (operator)
Count the number of events sent by the observed
Observable.just(1,2,3,4,5,9) .count() .subscribe(new Consumer<Long>() { @Override public void accept(Long aLong) throws Throwable { System.out.println(aLong); } });
4, Filter operator
1.filter operator
Specify filter conditions to filter the required events / data
Observable.just(1,2,3,4,5,6) .filter(new Predicate<Integer>() { @Override public boolean test(Integer integer) throws Throwable { return integer>4; } }).subscribe(new Consumer<Integer>() { @Override public void accept(Integer integer) throws Throwable { System.out.println(integer); } });
2.ofType operator
Filter events / data of the specified type
Observable.just("ha-ha",2,3,4,5,"Apple") .ofType(String.class) .subscribe(new Consumer<String>() { @Override public void accept(String s) throws Throwable { System.out.println(s); } });
3.skip operator
Events / data whose filtering conditions are not met
Observable.just("ha-ha",2,3,"camera",7,5,"Apple") .skip(4) .subscribe(new Consumer<Serializable>() { @Override public void accept(Serializable serializable) throws Throwable { System.out.println(serializable); } });
4. Distinct / distinct untilchanged operator
Filter out duplicate events / data
Distinct filters all duplicate elements
Observable.just("ha-ha",2,2,3,"camera",3,"camera",7,5,"Apple") .distinct() .subscribe(new Consumer<Serializable>() { @Override public void accept(Serializable serializable) throws Throwable { System.out.println(serializable); } });
Distinguishuntilchanged removes only the first duplicate element
Observable.just("ha-ha",2,2,2,3,"camera",3,"camera",7,"Apple") .distinctUntilChanged() .subscribe(new Consumer<Serializable>() { @Override public void accept(Serializable serializable) throws Throwable { System.out.println(serializable); } });
5.take operator
Filter events / data by time or quantity
Observable.just("ha-ha",2,2,2,3,"camera",3,"camera",7,"Apple") .take(4) .subscribe(new Consumer<Serializable>() { @Override public void accept(Serializable serializable) throws Throwable { System.out.println(serializable); } });
6.elementAt operator
Filter events at the specified location
Observable.just("ha-ha",2,2,2,3,"camera",3,"camera",7,"Apple") .elementAt(5) .subscribe(new Consumer<Serializable>() { @Override public void accept(Serializable serializable) throws Throwable { System.out.println(serializable); } });
7. Throttle first / throttle last operator
Filter events by event segment
Observable.create(new ObservableOnSubscribe<Integer>() { @Override public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Throwable { emitter.onNext(1);//First send Thread.sleep(500); emitter.onNext(2);//Do not send if the time does not exceed 1s Thread.sleep(500); emitter.onNext(3); //Time 500 + 500 is 1 s to send Thread.sleep(500); emitter.onNext(4); //Do not send if the time does not exceed 1s Thread.sleep(1500); emitter.onNext(5); //Sent after 1 s Thread.sleep(500); emitter.onNext(6);//Do not send if the time does not exceed 1s Thread.sleep(500); emitter.onNext(7);//Sent after 1 s } }) .throttleFirst(1, TimeUnit.SECONDS) .subscribe(new Consumer<Integer>() { @Override public void accept(Integer integer) throws Throwable { Log.e("---->" , ""+integer); } });
Observable.create(new ObservableOnSubscribe<Integer>() { @Override public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Throwable { emitter.onNext(1);//First, do not send Thread.sleep(500); emitter.onNext(2); Thread.sleep(500); emitter.onNext(3); Thread.sleep(500); emitter.onNext(4); Thread.sleep(1500); emitter.onNext(5); Thread.sleep(500); emitter.onNext(6); Thread.sleep(500); emitter.onNext(7); } }) .throttleLast(1, TimeUnit.SECONDS) .subscribe(new Consumer<Integer>() { @Override public void accept(Integer integer) throws Throwable { Log.e("---->" , ""+integer); } });
5, Filter operator
1.all operator
Judge whether all events meet the conditions
Observable.just(2,2,2,3,3,7,6,85) .all(new Predicate<Integer>() { @Override public boolean test(Integer integer) throws Throwable { return integer>=2; } }).subscribe(new Consumer<Boolean>() { @Override public void accept(Boolean aBoolean) throws Throwable { System.out.println(aBoolean); } });
2.takeWhile
When the sent event judgment conditions are not met, the subsequent event reception will be terminated. All data must meet the conditions before execution, otherwise it will not be executed
Observable.just(2,2,2,3,3,7,6,85) .takeWhile(new Predicate<Integer>() { @Override public boolean test(Integer integer) throws Throwable { return integer>=2; } }).subscribe(new Consumer<Integer>() { @Override public void accept(Integer integer) throws Throwable { System.out.println(integer); } });
3.skipWhile
Subsequent events are received only when the judgment conditions of the sent event are not met
Observable.just(2,2,2,3,3,7,6,85) .skipWhile(new Predicate<Integer>() { @Override public boolean test(Integer integer) throws Throwable { //It is equivalent to traversing each element to make judgment return integer>=4; } }).subscribe(new Consumer<Integer>() { @Override public void accept(Integer integer) throws Throwable { System.out.println(integer); } });
4.takeUntil
Filter events (the same as filter) and send the end condition of complete. Of course, this value will also be included before sending
Observable.just(1,2,3,45,56,7) .takeUntil(new Predicate<Integer>() { @Override public boolean test(Integer integer) throws Throwable { return integer==3; } }).subscribe(new Consumer<Integer>() { @Override public void accept(Integer integer) throws Throwable { System.out.println(integer); } });
5.skipUntil
When the observer subscribes to the original Observable, the operator will ignore the data transmitted by the original Observable. It will not start transmitting the data transmitted by the original Observable until the second Observable transmits a data.
Observable.just(1,2,3,45,56,7) .skipUntil(Observable.create(new ObservableOnSubscribe<String>() { @Override public void subscribe(@NonNull ObservableEmitter<String> emitter) throws Throwable { emitter.onNext("hahah"); System.out.println("I did it first"); } })).subscribe(new Consumer<Integer>() { @Override public void accept(Integer integer) throws Throwable { System.out.println(integer); } });
6.sequenceEqual
Judge whether the events of the two observers are the same
Observable<Integer> just1 = Observable.just(1,2,3); Observable<Integer> just2 = Observable.just(1,2,3,4); Observable.sequenceEqual(just1,just2) .subscribe(new Consumer<Boolean>() { @Override public void accept(Boolean aBoolean) throws Throwable { System.out.println(aBoolean); } });
7.contains
Judge whether the sent data contains the specified data
Observable.just(1,2,3,4,6,7) .contains(2) .subscribe(new Consumer<Boolean>() { @Override public void accept(Boolean aBoolean) throws Throwable { System.out.println(aBoolean); } });
8.isEmpty
Judge whether the sent data is empty
List<String> list = new ArrayList<>(); Observable.just(list) .isEmpty() .subscribe(new Consumer<Boolean>() { @Override public void accept(Boolean aBoolean) throws Throwable { System.out.println(aBoolean); } });
9.amb
Multiple observers only receive "the first observer who successfully sent data". When multiple observables need to be sent, only the Observable data that sent the data first will be accepted, and the remaining observables will be discarded
List<Observable<Integer>> list = new ArrayList<>(); Observable<Integer> just1 = Observable.just(1,2,3); Observable<Integer> just2 = Observable.just(1,2,3,4); list.add(just1); list.add(just2); Observable.amb(list) .subscribe(new Consumer<Integer>() { @Override public void accept(Integer integer) throws Throwable { System.out.println(integer); } });
6, Other operators
1. Common do series operators
1.doOnEach
Register an action to use for each data item transmitted by Observable
Observable.just(1,2,3) .doOnEach(new Consumer<Notification<Integer>>() { @Override public void accept(Notification<Integer> integerNotification) throws Throwable { System.out.println("integerNotification:"+integerNotification.toString()); } }) .subscribe(new Observer<Integer>() { @Override public void onSubscribe(@NonNull Disposable d) { System.out.println("onSubscribe : "+d); } @Override public void onNext(@NonNull Integer integer) { System.out.println("onNext :"+integer); } @Override public void onError(@NonNull Throwable e) { System.out.println("onError "+e); } @Override public void onComplete() { System.out.println("onComplete"); } });
2.doOnSubscribe
Register an action to use when the observer subscribes. Internally implemented by OperatorDoOnSubscribe
Observable.just(1,2,3) .doOnSubscribe(new Consumer<Disposable>() { @Override public void accept(Disposable disposable) throws Throwable { System.out.println("disposable:"+disposable.toString()); } }) .subscribe(new Observer<Integer>() { @Override public void onSubscribe(@NonNull Disposable d) { System.out.println("onSubscribe : "+d); } @Override public void onNext(@NonNull Integer integer) { System.out.println("onNext :"+integer); } @Override public void onError(@NonNull Throwable e) { System.out.println("onError "+e); } @Override public void onComplete() { System.out.println("onComplete"); } });
3.doOnNext
Observable.just(1,2,3) .doOnNext(new Consumer<Integer>() { @Override public void accept(Integer integer) throws Throwable { System.out.println("integer: "+integer); } }) .subscribe(new Observer<Integer>() { @Override public void onSubscribe(@NonNull Disposable d) { System.out.println("onSubscribe : "+d); } @Override public void onNext(@NonNull Integer integer) { System.out.println("onNext :"+integer); } @Override public void onError(@NonNull Throwable e) { System.out.println("onError "+e); } @Override public void onComplete() { System.out.println("onComplete"); } });
4.doAfterNext
Observable.just(1,2,3) .doAfterNext(new Consumer<Integer>() { @Override public void accept(Integer integer) throws Throwable { System.out.println("integer: "+integer); } }).subscribe(new Observer<Integer>() { @Override public void onSubscribe(@NonNull Disposable d) { System.out.println("onSubscribe : "+d); } @Override public void onNext(@NonNull Integer integer) { System.out.println("onNext :"+integer); } @Override public void onError(@NonNull Throwable e) { System.out.println("onError "+e); } @Override public void onComplete() { System.out.println("onComplete"); } });
5.doOnComplete
Register an action and use it for Observable completed normally
Observable.just(1,2,3) .doOnComplete(new Action() { @Override public void run() throws Throwable { System.out.println("Execute until I pull"); } }).subscribe(new Observer<Integer>() { @Override public void onSubscribe(@NonNull Disposable d) { System.out.println("onSubscribe : "+d); } @Override public void onNext(@NonNull Integer integer) { System.out.println("onNext :"+integer); } @Override public void onError(@NonNull Throwable e) { System.out.println("onError "+e); } @Override public void onComplete() { System.out.println("onComplete"); } });
6.doOnErro
Register an action to use the Observable with error
Observable.create(new ObservableOnSubscribe<Integer>() { @Override public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Throwable { emitter.onNext(121231); int a = 0; int b = 2/a; } }).doOnError(new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Throwable { System.out.println("Execute until I pull : "+throwable); } }).subscribe(new Observer<Serializable>() { @Override public void onSubscribe(@NonNull Disposable d) { System.out.println("onSubscribe : "+d); } @Override public void onNext(@NonNull Serializable serializable) { System.out.println("onNext :"+serializable); } @Override public void onError(@NonNull Throwable e) { System.out.println("onError "+e); } @Override public void onComplete() { System.out.println("onComplete"); } });
2. Error / exception handling
1.onErrorRetuturn
Catch exceptions and feed back special results & normal termination
If an exception occurs, print 100
Observable.create(new ObservableOnSubscribe<Integer>() { @Override public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Throwable { emitter.onNext(1); emitter.onNext(2); int a = 0; int b = 2/a; emitter.onNext(3); emitter.onNext(4); emitter.onNext(5); } }).onErrorReturn(new Function<Throwable, Integer>() { @Override public Integer apply(Throwable throwable) throws Throwable { return 100; } }).subscribe(new Consumer<Integer>() { @Override public void accept(Integer integer) throws Throwable { System.out.println(integer); } });
2.onErrorResumeNext
Catch the exception and return a new event
Observable.create(new ObservableOnSubscribe<Integer>() { @Override public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Throwable { emitter.onNext(1); emitter.onNext(2); int a = 0; int b = 2/a; emitter.onNext(3); emitter.onNext(4); emitter.onNext(5); } }).onErrorResumeNext(new Function<Throwable, ObservableSource<? extends Integer>>() { @Override public ObservableSource<? extends Integer> apply(Throwable throwable) throws Throwable { return Observable.just(11,22); } }).subscribe(new Consumer<Integer>() { @Override public void accept(Integer integer) throws Throwable { System.out.println(integer); } });
3.retry
Abnormal retry: the following code will print 1 and 2 indefinitely, and will loop dead
Observable.create(new ObservableOnSubscribe<Integer>() { @Override public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Throwable { emitter.onNext(1); emitter.onNext(2); int a = 0; int b = 2/a; emitter.onNext(3); emitter.onNext(4); } }).retry().subscribe(new Consumer<Integer>() { @Override public void accept(Integer integer) throws Throwable { System.out.println(integer); } });
3. Event recurrence
1.repeat
The repeat operator repeatedly generates multiple results for an Observable. When repeat() receives onComplete(), it will trigger a re subscription. By default, it runs on a new thread
Observable.range(0,2).repeat(2).subscribe(new Observer<Integer>() { @Override public void onSubscribe(@NonNull Disposable d) { Log.e("---->","Disposable:"+d); } @Override public void onNext(@NonNull Integer integer) { Log.e("---->","onNext:"+integer); } @Override public void onError(@NonNull Throwable e) { Log.e("---->","onError:"+e.getMessage()); } @Override public void onComplete() { Log.e("---->","onComplete:"); } });
2.repeatWhen
That is, subscribers can subscribe multiple times. For example, the first subscription 123 will be re subscribed after an interval of 3 seconds
Observable.just(1,2,3) .repeatWhen(new Function<Observable<Object>, ObservableSource<?>>() { @Override public ObservableSource<?> apply(Observable<Object> objectObservable) throws Throwable { return Observable.timer(3, TimeUnit.SECONDS); } }).subscribe(new Consumer<Integer>() { @Override public void accept(Integer integer) throws Throwable { Log.e("---->","integer:"+integer); } });
3.repeatUntil
The setting is repeated until the condition is judged
Observable.just(1,2) .repeatUntil(new BooleanSupplier() { @Override public boolean getAsBoolean() throws Throwable { boolean b; int rand = (int) (Math.random() * 10); //If the randomly generated integer is greater than 5, stop the repetition. Log.e("---->","rand:"+rand); if (rand > 5) { b = true; } else { b = false; } return b; } }).subscribe(new Consumer<Integer>() { @Override public void accept(Integer integer) throws Throwable { Log.e("---->","integer:"+integer); } });
4.delay
The function is the same as that of the timer operator, but delay is used in events to delay the sending of a certain event~
Must be implemented in the Android project:
Observable.just(1,2).delay(2, TimeUnit.SECONDS).subscribe(new Consumer<Integer>() { @Override public void accept(Integer integer) throws Throwable { Log.e("---->","Start execution" +integer); } });
5.timeout
If the original Observable does not transmit any data after a specified period of time, an exception is emitted or an alternate Observable is used.
Observable.create(new ObservableOnSubscribe<Integer>() { @Override public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Throwable { emitter.onNext(1); emitter.onNext(2); Thread.sleep(100); emitter.onNext(3); Thread.sleep(1000); emitter.onNext(4); emitter.onNext(5); emitter.onComplete(); } //If you do not specify an alternate Observable, an exception will be thrown }).timeout(999,TimeUnit.MICROSECONDS,Observable.just(99,100)) .subscribe(new Observer<Integer>() { @Override public void onSubscribe(@NonNull Disposable d) { Log.e("---->","Disposable: "+d); } @Override public void onNext(@NonNull Integer integer) { Log.e("---->","integer: "+integer); } @Override public void onError(@NonNull Throwable e) { Log.e("---->","Throwable: "+e.getMessage()); } @Override public void onComplete() { Log.e("---->","onComplete: "); } });
summary
Project address: https://github.com/renbin1990/RxjavaOperator