RxJava operator (seven) - filter operator

1. Introduction: The previous articles have introduced operators such as creation, conversion, and functions of RxJAva. Next, let's take a look at the remaining operators for conditional filtering.

Second, the role of the filter operator:

Filter/filter events sent by Observable & events received by Observer

Third, the classification of filter operators

Schematic

Fourth, the introduction of operators

  • filter()

  1. Function: filter the events sent according to the conditions, only those that meet the conditions will be sent
  2. Parameter: Predicate object. When it returns true, the event will be distributed. If it returns false, the sending will be ignored.
  3. Example of use
   Observable.just(1, 2, 3,4,5)
                .filter(new Predicate<Integer>() {
                    @Override
                    public boolean test(Integer integer) throws Exception {
                        return integer <= 3; // here the event is sent if the condition returns true
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer() {
                    @Override
                    public void accept(Object o) throws Exception {
                        Log.e("=====", o + "");
                    }
                });

Output result:

05-06 11:13:32.250 15316-15316/com.example.administrator.googleplay E/=====: 1
05-06 11:13:32.250 15316-15316/com.example.administrator.googleplay E/=====: 2
05-06 11:13:32.250 15316-15316/com.example.administrator.googleplay E/=====: 3
  • offType () 

  1. The effect is to filter according to the type of data sent
  2. Parameters: bytecode file.class indicates the data type that allows output
  3. Example of use
Observable.just(1, "A", 3,"C",5)
                .ofType(Integer.class) 
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer() {
                    @Override
                    public void accept(Object o) throws Exception {
                        Log.e("=====", o + "");
                    }
                });

Output result:

05-06 11:18:40.943 15316-15316/com.example.administrator.googleplay E/=====: 1
05-06 11:18:40.944 15316-15316/com.example.administrator.googleplay E/=====: 3
05-06 11:18:40.944 15316-15316/com.example.administrator.googleplay E/=====: 5

The output results are of type Integer, and the data of type String is filtered out.

  • skip()/ skipLast()

  1. Role: skip a certain number of events and send again
  2. Parameters: integer indicates the number of skips
  3. overload
//Parameters: time skip time, TimeUnit time unit
skip(long time, TimeUnit unit)
//Parameters: time skip time, TimeUnit time unit, Scheduler scheduler
skip(long time, TimeUnit unit, Scheduler scheduler)

    4. Example of use

Observable.just(1, "A", 3,"C",5)
                // express the number of skips
               .skip(2)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer() {
                    @Override
                    public void accept(Object o) throws Exception {
                        Log.e("=====", o + "");
                    }
                });

Output result:

05-06 11:27:39.211 15316-15316/com.example.administrator.googleplay E/=====: 3
05-06 11:27:39.211 15316-15316/com.example.administrator.googleplay E/=====: C
05-06 11:27:39.211 15316-15316/com.example.administrator.googleplay E/=====: 5

5. Example of skip overloading and skipLast usage

Observable.intervalRange(0,7,0,1,TimeUnit.SECONDS)
                 .skip(2,TimeUnit.SECONDS) //Skip the first two seconds of events
                .skipLast(2)//Skip the last two data
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer() {
                    @Override
                    public void accept(Object o) throws Exception {
                        Log.e("=====", o + "");
                    }
                });

Output result:

05-06 11:31:36.040 15316-15316/com.example.administrator.googleplay E/=====: 2
05-06 11:31:37.040 15316-15316/com.example.administrator.googleplay E/=====: 3
05-06 11:31:38.038 15316-15316/com.example.administrator.googleplay E/=====: 4

Output 7 numbers from 0, namely 0-6, filter the first two seconds of data 0 and 1, mention the last two data 5 and 6, and output the data between 2, 3, and 4;

  • distinct() / distinctUntilChanged()

  1. Role: filter the repeated data in the send event
  2. distinct() usage example
  Observable.just(1,2,4,3,3,4,4,5,5,5)
                .distinct()
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Exception {
                        Log.e("=====", integer + "");
                    }
                });

Output result:

05-06 11:41:41.712 16360-16360/com.example.administrator.googleplay E/=====: 1
05-06 11:41:41.712 16360-16360/com.example.administrator.googleplay E/=====: 2
05-06 11:41:41.712 16360-16360/com.example.administrator.googleplay E/=====: 4
05-06 11:41:41.712 16360-16360/com.example.administrator.googleplay E/=====: 3
05-06 11:41:41.713 16360-16360/com.example.administrator.googleplay E/=====: 5

Only one of the repeated 2, 3, 4, and 5 in the above-mentioned events is output, and the others are filtered out.

   3. distinctUntilChanged() only filters the continuous and repeated display of the first one

 Observable.just(1,2,4,3,3,4,4,5,5,5)
                .distinctUntilChanged()
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Exception {
                        Log.e("=====", integer + "");
                    }
                });

Output result:

05-06 11:44:28.338 16360-16360/com.example.administrator.googleplay E/=====: 1
05-06 11:44:28.338 16360-16360/com.example.administrator.googleplay E/=====: 2
05-06 11:44:28.338 16360-16360/com.example.administrator.googleplay E/=====: 4
05-06 11:44:28.338 16360-16360/com.example.administrator.googleplay E/=====: 3
05-06 11:44:28.338 16360-16360/com.example.administrator.googleplay E/=====: 4
05-06 11:44:28.338 16360-16360/com.example.administrator.googleplay E/=====: 5

This time the output is one more 4 than before, because the first 4 is repeated with the subsequent ones, but it is not repeated continuously, so it will be output, and the other continuous ones only output the first one

  • take () sum takeLast ()  

  1. Role: limit the number of events sent
  2. Parameters: the number of integers to limit
  3. Comparison of the two: take() positive sequence outputs a limited number of events takeLast() outputs the reciprocal number of events
  4. Example of use
Observable.just(1,2,4,3,3)
                .takeLast(3)
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Exception {
                        Log.e("=====", integer + "");
                    }
                });

Output result:

05-06 11:51:23.571 16360-16360/com.example.administrator.googleplay E/=====: 4
05-06 11:51:23.571 16360-16360/com.example.administrator.googleplay E/=====: 3
05-06 11:51:23.571 16360-16360/com.example.administrator.googleplay E/=====: 3
  • throttleFirst()/ throttleLast()

  1. Role: only send the first/last event within a limited time
  2. Parameters: time set time TimeUntil time unit
  3. Example of use:
Observable.intervalRange(0,7,0,1,TimeUnit.SECONDS)
                .throttleFirst(2,TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer() {
                    @Override
                    public void accept(Object o) throws Exception {
                        Log.e("=====", o + "");
                    }
                });

Output result:

05-06 11:56:03.752 17153-17153/com.example.administrator.googleplay E/=====: 0
05-06 11:56:06.734 17153-17153/com.example.administrator.googleplay E/=====: 3
05-06 11:56:09.734 17153-17153/com.example.administrator.googleplay E/=====: 6
  • throttleWithTimeout () / debounce()

  1. Function: When sending a data event, if the interval between two sending events is less than the specified time, the previous data will be discarded, and the next data will not be sent until no new data is transmitted within the specified time.
  2. Example of use
Observable.create(new ObservableOnSubscribe() {
            @Override
            public void subscribe(ObservableEmitter e) throws Exception {
                e.onNext(1); // send event 1
                Thread.sleep(500);
                e.onNext(2); // Send event 2 every 500 ms, event 1 will be replaced by 2
                Thread.sleep(1500); //Event 2 is sent every 1500 ms
                e.onNext(3); // send event 3
                Thread.sleep(500);
                e.onNext(4); // Send event 4 every 500 ms, event 3 will be replaced by 4
                Thread.sleep(500);
                e.onNext(5); // Send event 5 every 500 ms, event 4 will be replaced by 5 and output 5
            }
        }).throttleWithTimeout(1,TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer() {
                    @Override
                    public void accept(Object o) throws Exception {
                        Log.e("=====", o + "");
                    }
                });

According to the comment analysis in the code, the output result should be 2, 5, the output result of running the program:

05-06 13:14:25.902 18509-18509/com.example.administrator.googleplay E/=====: 2
05-06 13:14:28.406 18509-18509/com.example.administrator.googleplay E/=====: 5
  • firstElement / lastElement 

  1. Role: select only the 1st element / the last element
  2. Example of use
// get the first element
        Observable.just(1, 2, 3, 4, 5)
                  .firstElement()
                  .subscribe(new Consumer<Integer>() {
                     @Override
                    public void accept( Integer integer) throws Exception {
                        Log.d("====="+ integer);
                    }
                });

 // Get the last element Observable.just(1, 2, 3, 4, 5) .lastElement() .subscribe(new Consumer<Integer>() { @Override public void accept( Integer integer) throws Exception { Log. d("====="+ integer); } }); output 
 
05-06 13:14:25.902 18509-18509/com.example.administrator.googleplay E/=====: 1
05-06 13:14:28.406 18509-18509/com.example.administrator.googleplay E/=====: 5
  • elementAt()/ elementAtOrError()

  1. Role: only get the event sent at the specified location
  2. Parameters: index gets the subscript of the parameter starting from 0
  3. Overload index to get the subscript of the parameter starting from 0, the default value of Object, and the default value if the subscript is out of bounds
  4. Example of use
   Observable.just(1, 2, 3, 4, 5)
                  .elementAt (2)
                  .subscribe(new Consumer<Integer>() {
                      @Override
                      public void accept( Integer integer) throws Exception {
                          Log.d("====="+ integer);
                      }
        });

When the obtained position index > the length of the sending event sequence, set the default parameter
        Observable.just(1, 2, 3, 4, 5)
                .elementAt (6,10)
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept( Integer integer) throws Exception {
                      Log.d("====="+ integer);
                    }
                });

Output result:

05-06 13:14:25.902 18509-18509/com.example.administrator.googleplay E/=====: 3
05-06 13:14:28.406 18509-18509/com.example.administrator.googleplay E/=====: 10

The function of elementAtOrError() is the same as that of elementAt(), the subscript is not allowed to go out of bounds, and an exception will be thrown if the subscript goes out of bounds

The above is an introduction to the use of RxJava's filter operators. These operation methods play an important role in the processing of business logic in the development process.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325755683&siteId=291194637