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

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
带你搞懂Java结构化数据处理开源库SPL带你搞懂Java结构化数据处理开源库SPLMay 24, 2022 pm 01:34 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

Java集合框架之PriorityQueue优先级队列Java集合框架之PriorityQueue优先级队列Jun 09, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

完全掌握Java锁(图文解析)完全掌握Java锁(图文解析)Jun 14, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

一起聊聊Java多线程之线程安全问题一起聊聊Java多线程之线程安全问题Apr 21, 2022 pm 06:17 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

Java基础归纳之枚举Java基础归纳之枚举May 26, 2022 am 11:50 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

详细解析Java的this和super关键字详细解析Java的this和super关键字Apr 30, 2022 am 09:00 AM

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

java中封装是什么java中封装是什么May 16, 2019 pm 06:08 PM

封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。

Java数据结构之AVL树详解Java数据结构之AVL树详解Jun 01, 2022 am 11:39 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于平衡二叉树(AVL树)的相关知识,AVL树本质上是带了平衡功能的二叉查找树,下面一起来看一下,希望对大家有帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.