Table of Contents
1.Distinct
2.Filter
3.First
4.Last
5.ElementAt
6.Take
7.TakeLast
8.Sample
9.IgnoreElements
Home Java javaTutorial An in-depth explanation of the techniques of RxJava_04 [data transmission filtering operation]

An in-depth explanation of the techniques of RxJava_04 [data transmission filtering operation]

Mar 04, 2017 am 09:49 AM

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.

  1. Distinct - Remove duplicate data sent

  2. Filter - Filter specific data based on conditions

  3. First - Get the first data in the sending queue

  4. Last - Get the last data in the sending queue

  5. ElementAt - According to the index Send specific data in the queue

  6. Take - Get the first n items of data in the queue

  7. TakeLast - Get the last n items of data in the queue

  8. Sample - Send by sending time samples based on the data sent

  9. 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;
}
Copy after login

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);
        }
    });
Copy after login

The output is as follows:

IT520: call: Student{name=&#39;张三&#39;, age=16}
IT520: call: Student{name=&#39;李四&#39;, age=17}
IT520: call: Student{name=&#39;王二麻子&#39;, age=18}
Copy after login

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.");
            }
        });
Copy after login

Output

Next: 1
Next: 2
Next: 3
Sequence complete.
Copy after login

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.");
    }
});
Copy after login

Output

Next: 1
Sequence complete.
Copy after login

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.");
    }
});
Copy after login

Output

Next: 3
Sequence complete.
Copy after login

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);
        }
    });
Copy after login

Output

com.m520it.rxjava I/IT520: call: 4
Copy after login

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.");
            }
        });
Copy after login

Output

Next: 1
Next: 2
Next: 3
Next: 4
Sequence complete.
Copy after login

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.");
            }
        });
Copy after login

Output

Next: 5
Next: 6
Next: 7
Next: 8
Sequence complete.
Copy after login

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);
            }
        });
Copy after login

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);
                }
            });
Copy after login

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)!


Statement of this Website
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

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

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

React API Call Guide: How to interact and transfer data with the backend API React API Call Guide: How to interact and transfer data with the backend API Sep 26, 2023 am 10:19 AM

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

How to transfer all data between two iPhones Detailed explanation: How to migrate data from old phones How to transfer all data between two iPhones Detailed explanation: How to migrate data from old phones Mar 18, 2024 pm 06:31 PM

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 &quot;transfer all&quot; the data. This issue's article List several ways to &quot;transfer part of the data&quot;. 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.

Using HTTPS for data transmission in Java API development Using HTTPS for data transmission in Java API development Jun 18, 2023 pm 10:43 PM

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

PHP trait DTO: a key tool for optimizing the data transfer process PHP trait DTO: a key tool for optimizing the data transfer process Oct 12, 2023 pm 03:10 PM

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

Using RxJava for asynchronous processing in Java API development Using RxJava for asynchronous processing in Java API development Jun 18, 2023 pm 06:40 PM

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

PHP trait DTO: a key tool for optimizing the data transfer process PHP trait DTO: a key tool for optimizing the data transfer process Oct 12, 2023 pm 02:33 PM

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 Java development: How to use RxJava for reactive programming Sep 22, 2023 am 08:49 AM

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

How do C++ functions implement data transmission in network programming? How do C++ functions implement data transmission in network programming? Apr 27, 2024 pm 05:06 PM

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.

See all articles