Home  >  Article  >  Java  >  A detailed introduction to the code of RxJava_05 [Conversion Operations & Mathematical Operations]

A detailed introduction to the code of RxJava_05 [Conversion Operations & Mathematical Operations]

黄舟
黄舟Original
2017-03-04 09:54:531236browse

This tutorial is a comprehensive explanation based on the RxJava1.x version. Subsequent courses will be updated one after another, so stay tuned...

Between the observer and the observed, some transmitted data needs to be converted before it can be used. For example: sometimes we get the list of students in a certain class in the school, but we need to know the ranking of their Chinese scores. This requires converting the ArrayList into an ArrayList queue.

The following provides a series of data switching operators:

  1. Buffer - Turn multiple data sent into data sent to n queues, each queue The maximum length is the parameter size specified by the buffer() function.

  2. Window - periodically breaks the data from the original Observable into an Observable window.

  3. Map - divides the data sent by a certain Convert to another data

  4. flatMap - actually converts one type of data sent into an object of another data type

  5. GroupBy - Store the same type of sent data into n sub-Observables according to the specified key.

  6. Scan - Run a certain function on all the sent data, calculate the nth and n+1 items, and then run the calculated results with the n+2 items. An analogy.

1.Buffer

For example, in the following data, three strings are sent respectively

Observable.just("Hello Android !", "Hello Java", "Hello C");

If we add a buffer operation after the observer symbol, and specify cache 2 items, the code is as follows:

final Observable observable = Observable.just("Hello Android !", "Hello Java", "Hello C");
Observable> bufferObservable = observable.buffer(2);

Then it will send 2 List data for the first time, which are:

List<String>(){"Hello Android !", "Hello Java"}
List<String>(){"Hello C"}

The complete sample code below is as follows:

//这里模拟正常发送三个单一值的被观察者
final Observable observable = Observable.just("Hello Android !", "Hello Java", "Hello C");
//定义一个缓存的被观察者 每次缓存2个 缓存的数据自上面observable对象获取
Observable> bufferObservable = observable.buffer(2);
//订阅对象并获取缓存被观察者发送出来的数据
bufferObservable.subscribe(new Action1>() {
    @Override
    public void call(List strings) {
        Log.i(TAG, "call:--------");
        for (int i = 0; i < strings.size(); i++) {
            Log.i(TAG, "call: "+strings.get(i));
        }
    }
});

Output

call:--------
call: Hello Android !
call: Hello Java
call:--------
call: Hello C

buffer() actually converts the n data sent into x queues for sending

2.Window

Regularly decompose the data from the original Observable into an Observable window, and emit these windows instead of emitting one piece of data each time

Window is similar to Buffer, but instead of emitting data packets from the original Observable, it emits are Observables, each of these Observables emits a subset of the original Observable data, and finally emits an onCompleted notification.

Observable.just(1, 2, 3, 4, 5)
//将一个Observable发射出去的数据分解为多个Observable对象 每个Observable发射2个数据
            .window(2)
            .subscribe(new Action1<Observable<Integer>>() {
                @Override
                public void call(Observable<Integer> innerObservable) {
                    Log.i(TAG, "call: ---------");
                    innerObservable.subscribe(new Action1<Integer>() {
                        @Override
                        public void call(Integer value) {
                            Log.i(TAG, "call: "+value);
                        }
                    });
                }
            });

Output:

 call: ---------
 call: 1
 call: 2
 call: ---------
 call: 3
 call: 4
 call: ---------
 call: 5

3.Map

School freshmen check-in. During data entry, it was discovered that Zhang San’s name was entered incorrectly and should be changed to Zhang Sanfeng. Now we need to re-enter the information for him. The code is as follows:

private ArrayList initPersons() {
    ArrayList<Student> persons = new ArrayList<>();
    persons.add(new Student("张三", 16));
    persons.add(new Student("李四", 17));
    persons.add(new Student("王二麻子", 18));
    return persons;
}

ArrayList<Student> students = initPersons();
for (int i = 0; i < students.size(); i++) {
    Student student = students.get(i);
    if (student.name.equals("张三")){
        student.name="张三丰";
    }
}

RxJava converts like this:

Observable.from(initPersons())
            //将张三的名字改为张三丰
            .map(new Func1<Student, Student>() {
                @Override
                public Student call(Student student) {
                     //循环检查每个学生的名字,如果找到张三 则改为张三丰
                    if (student.name.equals("张三")){
                        student.name="张三丰";
                    }
                    return student;
                }
            })
            .subscribe(new Action1<Student>() {
                @Override
                public void call(Student student) {
                    Log.i(TAG, "call: "+student);
                }
            });

map() actually converts a certain sent data into another data

4.FlatMap

The school formed a gymnastics team today. The school has recruited a few more students and the code is as follows:

private ArrayList<Student> initStudents() {
    ArrayList<Student> persons = new ArrayList<>();
    persons.add(new Student("张三", 11));
    persons.add(new Student("李四", 12));
    persons.add(new Student("王二麻子", 13));
    persons.add(new Student("李雷", 19));
    persons.add(new Student("韩梅梅", 18));
    persons.add(new Student("韩红", 17));
    return persons;
}

The superiors require that learning gymnastics should start from childhood. Let us find students younger than 15 years old, form a gymnastics team, and create a specific team for primary school students. of primary school students.

public static class LittleStudent extends Student{

    public LittleStudent(String name, int age) {
        super(name, age);
    }
}

So the code is as follows:

ArrayList<Student> students = initStudents();

//封装小学生集合
ArrayList<LittleStudent> littleStudents=new ArrayList<>();
for (int i = 0; i < students.size(); i++) {
    Student student = students.get(i);
    if (student.age<15){
        littleStudents.add(new LittleStudent(student.name,student.age));
    }
}

RxJava converts it like this:

Observable.from(initStudents())
            .flatMap(new Func1<Student, Observable<LittleStudent>>() {
                @Override
                public Observable<LittleStudent> call(Student student) {
                    if (student.age<15){
                        return Observable.just(new LittleStudent(student.name,student.age));
                    }
                    return null;
                }
            })
            .subscribe(new Action1<LittleStudent>() {
                @Override
                public void call(LittleStudent littleStudent) {
                    Log.i(TAG, "call: "+littleStudent);
                }
            });

flatMap() actually converts one type of data sent into another data Object of type

5.GroupBy

Splits an Observable into a collection of Observables, each of which emits a subsequence of the original Observable. Which data item is emitted by which Observable is determined by the function inside groupBy. This function assigns a Key to each item. Data with the same Key will be emitted by the same Observable. It returns a special subclass of Observable, GroupedObservable. Objects that implement the GroupedObservable interface have an additional method getKey. This Key is used to group data into the specified Observable.

//模拟学校录入的一系列的同名学生信息
private Observable<Person> getPersons(){
    return Observable.from(new Person[]{
            new Person("zhangsan",18),
            new Person("zhangsan",20),
            new Person("lisi",19),
            new Person("lisi",33),
            new Person("wangwu",20),
            new Person("wangwu",22),
            new Person("wangwu",21)
    });
}

Implement classification call

final Observable<GroupedObservable<String, Person>> observable = getPersons()
        //根据用户的名称来归类
        .groupBy(new Func1<Person, String>() {
            @Override
            public String call(Person person) {
                return person.name;
            }
        });
observable.subscribe(new Action1<GroupedObservable<String, Person>>() {
    //每归一类 则调用一次该方法
    @Override
    public void call(GroupedObservable<String, Person> observablelist) {
        Log.i(TAG, "call: ----"+observablelist.getKey());
        //打印队列中的每个元素
        observablelist.subscribe(new Action1<Person>() {
            @Override
            public void call(Person person) {
                Log.i(TAG, "call: "+person.name+"  "+person.age);
            }
        });

    }
});

Save the same type of sending data into n sub-Observables according to the specified key

6.Scan

The Scan operator applies a function to the first item emitted by the original Observable, and then emits the result of that function as its own first item. It fills the function's result with the second data into the function to generate its own second data. It continues this process to generate the remaining data sequence. This operator is called an accumulator in some cases.

For example, if we want to add from 1 to 5, the idea is as follows:

 1+2=3;
 3+3=6;
 6+4=10;
10+5=15;

RxJava converts like this:

//实现从1加到5的总数
Observable.just(1, 2, 3, 4, 5)
    .scan(new Func2<Integer, Integer, Integer>() {
        //定义每个子项的合并规则
        @Override
        public Integer call(Integer sum, Integer item) {
            return sum + item;
        }
    })
    .subscribe(new Action1<Integer>() {
        @Override
        public void call(Integer result) {
            Log.i(TAG, "call: " + result);
        }
    });

Output

Next: 1
Next: 3
Next: 6
Next: 10
Next: 15
Sequence complete.

Yes All the sent data is run through a function, and the nth and n+1 items are calculated. The calculated results are then run with the n+2 items, and so on.


During the development process, it is inevitable to use some common mathematical calculations, such as calculating the average/summation/maximum and minimum values ​​of a queue/getting the number, etc.

Regarding mathematical calculations, RxJava provides here A dependency package. The download address is RxJavaMath

The development package provides a core helper class:MathObservable

7.Average

Find the average of a certain queue Number, this queue can be of int type or double type, etc. The following example calculates the average number from 1 to 6

Observable<Integer> o1 = 
           MathObservable.averageInteger(Observable.just(1,2,3,4,5,6));
o1.subscribe(new Action1<Integer>() {
    @Override
    public void call(Integer integer) {
        Log.i(TAG, "call: "+integer);
    }
});

8.Max/Min

The Min operator operates on an Observable that emits values ​​and emits a single value: the smallest value.
The Max operator operates an Observable that emits values ​​and emits a single value: the largest value.

以下例子列出1到6的最小值:

Observable<Integer> o1 =
            MathObservable.min(Observable.just(1,2,3,4,5,6));

o1.subscribe(new Action1<Integer>() {
    @Override
    public void call(Integer integer) {
        Log.i(TAG, "call: "+integer);
    }
});

以下例子列出1到6的最大值:

Observable<Integer> o1 =
            MathObservable.max(Observable.just(1,2,3,4,5,6));

o1.subscribe(new Action1<Integer>() {
    @Override
    public void call(Integer integer) {
        Log.i(TAG, "call: "+integer);
    }
});

9.Count

count函数主要列出发送队列的个数。

Observable<Integer> o1 =Observable.just(1,2,3,4,5,4);
Observable<Integer> count = o1.count();

count.subscribe(new Action1<Integer>() {
    @Override
    public void call(Integer integer) {
            //打印出6
        Log.i(TAG, "call: "+integer);
    }
});

10.Sum

计算Observable发射的数值的和并发射这个和.

RxJava的实现是sumDouble, sumFloat, sumInteger, sumLong,它们不是RxJava核心模块的一部分,属于rxjava-math模块。你可以使用一个函数,计算Observable每一项数据的函数返回值的和。

Observable<Integer> o1 =
            MathObservable.sumInteger(Observable.just(1,2,3,4,5,4));

o1.subscribe(new Action1<Integer>() {
    @Override
    public void call(Integer integer) {
        Log.i(TAG, "call: "+integer);
    }
});

 以上就是深入浅出RxJava_05[转换操作&数学运算]的代码详细介绍的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn