


A 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:
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.
Window - periodically breaks the data from the original Observable into an Observable window.
Map - divides the data sent by a certain Convert to another data
flatMap - actually converts one type of data sent into an object of another data type
GroupBy - Store the same type of sent data into n sub-Observables according to the specified key.
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 Observableobservable = 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 Observableobservable = 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)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
