RxJava uses operators (2) - transformation operators

1 Introduction

I believe that every student who has used RxJava has a deep understanding of the power of RxJava. After introducing the basic creation operators, we will continue to look at the transformation operators. It is precisely because of the existence of transformation operators that RxJava can meet different scenarios. function.

The role of the transformation operator : process (ie, transform) the events in the event sequence/the entire event sequence so that it can be transformed into a different event/the entire event sequence

2. Operator type

  • map()
  • flatMap() 
  • ConcatMap ()
  • buffer ()

3. Introduction

  • map

(1) Each data sent by the observed is processed by a fixed function and returns a certain data type

(2) Usage scenarios - data type conversion

(3) Concrete examples, convert numbers to strings:

Observable.just(1, 2, 3)
                .map(new Function<Integer, String>() {
                    @Override
                    public String apply(Integer integer) throws Exception {
                        return String.valueOf(integer);
                    }
                }).subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                
            }
        });
As can be seen from the above, map() converts the Integer type object in the parameter into a String type object and returns it, and the parameter type of the event is also converted to String


  • flatMap

(1) Split the event sequence sent by the observer & convert it separately, merge it into a new event sequence, and finally send it

(2) Principle:

  • Create an Observable object for each event in the dispatch sequence
  • Execute the corresponding method for each Observable object created to replace and store
  • Combine the transformed Observable objects into an object and send it to the observer

(3) Usage scenario - split the sent event and replace it with a new event

(4) Concrete example - convert each number to a set and add a 0

Observable.just(1, 2, 3)
                .flatMap(new Function<Integer, ObservableSource<Integer>>() {
                    @Override
                    public ObservableSource<Integer> apply(Integer integer) throws Exception {
                        ArrayList<Integer> list = new ArrayList<>();
                        list.add(0);
                        list.add(integer);
                        return Observable.fromIterable(list);
                    }
                }).subscribe(new Consumer<Integer>() {
            @Override
            public void accept(Integer integer) throws Exception {

            }
        });

Output result:


Note: The order of output at this time is unordered

  • ConcatMap 

(1) The function is the same as flatMap(), except that  the sequence of events generated by splitting & re-merging = the sequence produced by the old sequence of the observer

(2) The principle is the same as flatMap

(3) Usage scenario - split the sent event and replace it with a new event

(4) Concrete example - convert each number to a set and add a 0

Observable.just(1, 2, 3)
                .flatMap(new Function<Integer, ObservableSource<Integer>>() {
                    @Override
                    public ObservableSource<Integer> apply(Integer integer) throws Exception {
                        ArrayList<Integer> list = new ArrayList<>();
                        list.add(0);
                        list.add(integer);
                        return Observable.fromIterable(list);
                    }
                }).subscribe(new Consumer<Integer>() {
            @Override
            public void accept(Integer integer) throws Exception {

            }
        });

Output result:

05-02 20:16:09.046 15718-15718/com.example.administrator.glide E/concatMap========: 0
05-02 20:16:09.046 15718-15718/com.example.administrator.glide E/concatMap========: 1
05-02 20:16:09.046 15718-15718/com.example.administrator.glide E/concatMap========: 2
05-02 20:16:09.046 15718-15718/com.example.administrator.glide E/concatMap========: 0
05-02 20:16:09.046 15718-15718/com.example.administrator.glide E/concatMap========: 1
05-02 20:16:09.047 15718-15718/com.example.administrator.glide E/concatMap========: 2
05-02 20:16:09.047 15718-15718/com.example.administrator.glide E/concatMap========: 0
05-02 20:16:09.047 15718-15718/com.example.administrator.glide E/concatMap========: 1
05-02 20:16:09.047 15718-15718/com.example.administrator.glide E/concatMap========: 2

Note: The order of output at this time is in accordance with the order of event distribution

  • buffer 

(1) Regularly take out fixed events from the observed and put them in the buffer area and send them together

(2) Principle:

  • Get events according to the set buffer size and step size
  • send buffer events

(3) Usage scenarios - events sent by the cache

(4) Example of use - sending data

Observable.just(1,2,3,4,5)
                .buffer(3,1)
                .subscribe(new Consumer<List<Integer>>() {
                    @Override
                    public void accept(List<Integer> integers) throws Exception {
                        
                    }
                });

Output result:

05-02 20:16:09.050 15718-15718/com.example.administrator.glide E/buffer=========: 1
05-02 20:16:09.050 15718-15718/com.example.administrator.glide E/buffer=========: 2
05-02 20:16:09.050 15718-15718/com.example.administrator.glide E/buffer=========: 3
05-02 20:16:09.050 15718-15718/com.example.administrator.glide E/buffer=========: 2
05-02 20:16:09.050 15718-15718/com.example.administrator.glide E/buffer=========: 3
05-02 20:16:09.051 15718-15718/com.example.administrator.glide E/buffer=========: 4
05-02 20:16:09.051 15718-15718/com.example.administrator.glide E/buffer=========: 3
05-02 20:16:09.052 15718-15718/com.example.administrator.glide E/buffer=========: 4
05-02 20:16:09.052 15718-15718/com.example.administrator.glide E/buffer=========: 5
05-02 20:16:09.053 15718-15718/com.example.administrator.glide E/buffer=========: 4
05-02 20:16:09.054 15718-15718/com.example.administrator.glide E/buffer=========: 5
05-02 20:16:09.054 15718-15718/com.example.administrator.glide E/buffer=========: 5

4. Development examples

Realize the request for automatic login after registration, business logic

  • Verify registration information
  • Initiate a login request after successful registration
  • Verify login information
  • Successful landing

Simulate a registration request and register a user account:

final Observable<User> observableLogin = Observable.create(new ObservableOnSubscribe() {
            @Override
            public void subscribe(ObservableEmitter e) throws Exception {
                e.onNext(new User("AAAAA","123"));
            }
        });

Simulate login request:

Observable<User> observableRegister = Observable.create(new ObservableOnSubscribe() {
            @Override
            public void subscribe(ObservableEmitter e) throws Exception {
                e.onNext(new User("AAAAA","123"));
            }
        });

Implement business logic:

observableRegister.filter(new Predicate<User>() {
            @Override
            public boolean test(User user) throws Exception {
                return user.getName().equals("AAAAA");
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Consumer<User>() {
                    @Override
                    public void accept(User user) throws Exception {
                        Log.e("========",user.getName()+"registered successfully");
                    }
                }).observeOn(Schedulers.io())
                .flatMap(new Function<User, ObservableSource<User>>() {
                    @Override
                    public ObservableSource<User> apply(User user) throws Exception {
                        return observableLogin;
                    }
                }).filter(new Predicate<User>() {
            @Override
            public boolean test(User user) throws Exception {
                return user.getName().equals("AAAAA") && user.getPswd().equals("123");
            }
        }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<User>() {
                    @Override
                    public void accept(User user) throws Exception {
                        Log.e("========",user.getName() + "Login successful");
                    }
                });

The above process uses observableRegister to verify whether the registration information is "AAAAA" during registration. After the verification is successful, the registration is completed. After the registration is successful, it is switched to the logged-in observer object to complete the login function.

Output result:

05-03 01:36:40.142 2310-2310/? E/========: AAAAA registration succeeded
05-03 01:36:40.316 2310-2310/? E/========: AAAAA login successfully

This use will play a big role in the usual business logic, which can make the code logic clearer while achieving better performance.

Guess you like

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