


An in-depth explanation of the techniques of RxJava_04 [data transmission filtering operation]
This tutorial is a comprehensive explanation based on the RxJava1.x version. Subsequent courses will be updated one after another, so stay tuned...
When the observer sends data to the observer, the data may need to be further filtered during data transmission. The following tutorial covers functions for most filtering operations.
Distinct - Remove duplicate data sent
Filter - Filter specific data based on conditions
First - Get the first data in the sending queue
Last - Get the last data in the sending queue
ElementAt - According to the index Send specific data in the queue
Take - Get the first n items of data in the queue
TakeLast - Get the last n items of data in the queue
Sample - Send by sending time samples based on the data sent
IgnoreElements - Ignore the sent data queue
1.Distinct
There is now a class, and the student information has been entered into the student system. It turned out that the same data was repeated. The student data queue is as follows:
private ArrayList<Student> initPersons() { ArrayList<Student> persons = new ArrayList<>(); persons.add(new Student("张三", 16)); persons.add(new Student("李四", 17)); persons.add(new Student("王二麻子", 18)); persons.add(new Student("张三", 22)); return persons; }
The current need is to intercept objects with duplicate names. And print it out:
Observable .from(initPersons()) //过滤重复名字的项 .distinct(new Func1<Student, String>() { @Override public String call(Student student) { return student.name; } }) .subscribe(new Action1<Student>() { @Override public void call(Student student) { Log.i(TAG, "call: "+student); } });
The output is as follows:
IT520: call: Student{name='张三', age=16} IT520: call: Student{name='李四', age=17} IT520: call: Student{name='王二麻子', age=18}
2.Filter
In addition to filtering out the repeated parts of the passed data, you can also clear specific ones according to the rules through filter The data.
The data sent by the following code is 12345. The filtering rule is that the data bar must be less than 4. The sample code is as follows:
Observable.just(1, 2, 3, 4, 5) .filter(new Func1<Integer, Boolean>() { @Override public Boolean call(Integer item) { return( item < 4 ); } }) .subscribe(new Subscriber<Integer>() { @Override public void onNext(Integer item) { System.out.println("Next: " + item); } @Override public void onError(Throwable error) { System.err.println("Error: " + error.getMessage()); } @Override public void onCompleted() { System.out.println("Sequence complete."); } });
Output
Next: 1 Next: 2 Next: 3 Sequence complete.
3.First
Calling this function allows the sent data queue to send only the first item.
Sample code
Observable.just(1, 2, 3) .first() .subscribe(new Subscriber<Integer>() { @Override public void onNext(Integer item) { System.out.println("Next: " + item); } @Override public void onError(Throwable error) { System.err.println("Error: " + error.getMessage()); } @Override public void onCompleted() { System.out.println("Sequence complete."); } });
Output
Next: 1 Sequence complete.
Similar functions include firstOrDefault(). This function is used to find if the queue is null during the queue sending process. If the first item is not reached, a default value will be sent.
4.Last
Calling this function allows the sent data queue to send only the last item.
Sample code
Observable.just(1, 2, 3) .last() .subscribe(new Subscriber<Integer>() { @Override public void onNext(Integer item) { System.out.println("Next: " + item); } @Override public void onError(Throwable error) { System.err.println("Error: " + error.getMessage()); } @Override public void onCompleted() { System.out.println("Sequence complete."); } });
Output
Next: 3 Sequence complete.
Similar functions include lastOrDefault(T)
5.ElementAt
ElementAt operator obtains the data item at the specified index position of the data sequence emitted by the original Observable, and then emits it as its own unique data.
If you pass a negative number, or the number of data items in the original Observable is less than index+1, an IndexOutOfBoundsException will be thrown.
The sample code is as follows:
Observable.just(1, 2, 3, 4, 1, 4) .elementAt(3) .subscribe(new Action1<Integer>() { @Override public void call(Integer value) { Log.i(TAG, "call: " + value); } });
Output
com.m520it.rxjava I/IT520: call: 4
6.Take
Using the Take operator allows you to modify the behavior of the Observable and only return the previous N items of data, and then transmit the completion notification, ignoring the remaining data.
Sample code
Observable.just(1, 2, 3, 4, 5, 6, 7, 8) .take(4) .subscribe(new Subscriber<Integer>() { @Override public void onNext(Integer item) { System.out.println("Next: " + item); } @Override public void onError(Throwable error) { System.err.println("Error: " + error.getMessage()); } @Override public void onCompleted() { System.out.println("Sequence complete."); } });
Output
Next: 1 Next: 2 Next: 3 Next: 4 Sequence complete.
7.TakeLast
Use the TakeLast operator to modify the original Observable, you can only emit the Observable's emitted last N item data, ignoring the previous data.
Sample code
Observable.just(1, 2, 3, 4, 5, 6, 7, 8) .takeLast(4) .subscribe(new Subscriber<Integer>() { @Override public void onNext(Integer item) { System.out.println("Next: " + item); } @Override public void onError(Throwable error) { System.err.println("Error: " + error.getMessage()); } @Override public void onCompleted() { System.out.println("Sequence complete."); } });
Output
Next: 5 Next: 6 Next: 7 Next: 8 Sequence complete.
8.Sample
Sample and send the sent data at a certain frequency
Observable .interval(1000, TimeUnit.MILLISECONDS)//每秒发送1个数字 .sample(2000,TimeUnit.MILLISECONDS)//每2秒采样一次 .subscribe(new Action1<Long>() { @Override public void call(Long aLong) { Log.i(TAG, "call: "+aLong); } });
Above The code prints: 0, 2, 4, 6, 8. . . .
9.IgnoreElements
If you don't care about the data emitted by an Observable, but want to be notified when it completes or terminates with an error, you can use the ignoreElements operator on the Observable, It ensures that the observer's onNext() method is never called.
Observable.just(1, 2, 3, 4, 1) .ignoreElements()//不发送任何信息 直接发送onCompleted() .subscribe(new Subscriber<Integer>() { @Override public void onCompleted() { Log.i(TAG, "onCompleted: "); } @Override public void onError(Throwable e) { } @Override public void onNext(Integer integer) { Log.i(TAG, "onNext: "+integer); } });
The above is an in-depth introduction to the techniques of RxJava_04 [data transmission filtering operation]. For more related content, please pay attention to the PHP Chinese website (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

ReactAPI Call Guide: How to interact with and transfer data to the backend API Overview: In modern web development, interacting with and transferring data to the backend API is a common need. React, as a popular front-end framework, provides some powerful tools and features to simplify this process. This article will introduce how to use React to call the backend API, including basic GET and POST requests, and provide specific code examples. Install the required dependencies: First, make sure Axi is installed in the project

When many friends change their Apple phones, they want to import all the data in the old phone to the new phone. In theory, it is completely feasible, but in practice, it is impossible to "transfer all" the data. This issue's article List several ways to "transfer part of the data". 1. iTunes is a pre-installed software on Apple mobile phones. It can be used to migrate all data in old mobile phones, but it needs to be used in conjunction with a computer. The migration can be completed by installing iTunes on the computer, then connecting the phone and computer via a data cable, using iTunes to back up the apps and data in the phone, and finally restoring the backup to the new Apple phone. 2. iCloudiCloud is Apple’s exclusive “cloud space” tool. You can log in to your old phone first.

With the development of science and technology, network communication has become one of the important tools for information transmission in modern society. But at the same time, information transmission on the network faces the risk of malicious attacks and theft, so security is particularly important. Based on this, the HTTPS protocol came into being. It is a protocol that adds SSL/TLS encryption to the HTTP protocol to ensure network transmission security. As a language widely used in network development, Java naturally provides a rich API to support the HTTPS protocol. This article will

PHPtraitDTO: A key tool for optimizing the data transmission process. Specific code examples are required. Introduction: During the development process, data transmission is a very common requirement, especially when data is transferred between different levels. In the process of transmitting this data, we often need to process, verify or convert the data to meet different business needs. In order to improve the readability and maintainability of the code, we can use PHPtraitDTO (DataTransferObject) to optimize

Java is a very popular programming language, especially widely used in web applications and mobile applications. When faced with some complex multi-threaded application development requirements, developers usually encounter many problems. RxJava is a very powerful library that provides asynchronous and event-based programming patterns based on the observer pattern. This article will introduce how to use RxJava for asynchronous processing in JavaAPI development. 1. What is RxJava? RxJava is a library based on the observer pattern

PHPtraitDTO: A key tool for optimizing the data transfer process, specific code examples are required Overview: In PHP development, data transfer is a very common task, such as passing data from the controller to the view, passing data from the interface to the front end, etc. However, in the process of transmitting data, the data often needs to be processed, converted and encapsulated, which may lead to code redundancy and difficulty in maintaining. To solve this problem, we can use PHPtraitDTO (DataTransfer

Java development: How to use RxJava for reactive programming, specific code examples are required. Introduction: With the increasing needs of modern software development, traditional programming methods can no longer meet the requirements for high concurrency, asynchronous processing, and event-driven characteristics. In order to solve these problems, reactive programming came into being. As a powerful reactive programming library, RxJava provides rich operators and flexible asynchronous processing methods, which greatly improves development efficiency and application scalability. This article will introduce how to use RxJava to

C++'s network data transfer functions include recv() and send(), which are used to receive and send data on the server side. The following steps demonstrate the process of using recv() and send() to create an echo server: 1. Create a socket; 2. Set the server address information; 3. Bind the socket to the server address; 4. Listen for connections; 5 .Accept the connection, receive data and send it back to the client in a loop; 6. Close the connection and socket.
