Filter operator
The .filter operator in RxJava is used to emit only those items from an Observable that satisfy a certain condition. In other words, it allows you to filter the emissions based on a predicate (a condition).
1. What Does .filter Do?
.filter Do?The .filter operator applies a given predicate function to each emitted item and only passes on the items that meet the criteria. If the predicate evaluates to true for an item, the item is emitted to the observer. If it evaluates to false, the item is skipped.
2. When to Use .filter?
.filter?You use .filter when you want to work only with a subset of the data being emitted by an Observable. For example:
Filtering out numbers greater than a certain value.
Filtering a list of objects based on a property (like filtering people above a certain age).
Removing unwanted values, like filtering out nulls or negative numbers.
3. Syntax of .filter in Kotlin (RxJava 2/3)
.filter in Kotlin (RxJava 2/3)Here’s the basic syntax:
observable.filter { item ->
// Predicate that returns true for items you want to keep
}4. Example Program: Filtering a List of Integers
Let’s create a simple Kotlin program where we use the .filter operator to filter out numbers from a list. The goal will be to emit only the even numbers from the list.
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
fun main() {
// Create an Observable from a list of integers
val numbersObservable = Observable.fromIterable(listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
// Apply the filter operator to emit only even numbers
numbersObservable
.filter { number -> number % 2 == 0 } // Predicate to filter even numbers
.subscribeOn(Schedulers.io()) // Subscribe on background thread
.observeOn(AndroidSchedulers.mainThread()) // Observe on main thread
.subscribe(
{ result -> println("Filtered number: $result") }, // onNext
{ error -> println("Error: ${error.message}") }, // onError
{ println("All numbers processed!") } // onComplete
)
}Explanation:
Observable.fromIterable(): This creates an observable from the provided list of integers (from 1 to 10).
.filter { number -> number % 2 == 0 }: This is the filtering logic. We use the modulo operator (
%) to filter even numbers. Only numbers that are divisible by 2 (i.e.,number % 2 == 0) will pass through.subscribeOn(Schedulers.io()): Specifies that the filtering operation should be done on a background thread (I/O thread).
observeOn(AndroidSchedulers.mainThread()): Specifies that the results should be observed on the main thread (this would be important in an Android application to update the UI).
subscribe(): Subscribes to the filtered observable, providing
onNext,onError, andonCompletehandlers.
Output:
As you can see, only the even numbers (2, 4, 6, 8, 10) are emitted and processed by the observer.
5. Real-World Example: Filtering a List of Strings
Let’s enhance the example to filter a list of strings. In this case, we'll filter a list of names and emit only those names that start with the letter "A".
Explanation:
.filter { name -> name.startsWith("A") }: This filtering condition ensures that only the names starting with the letter "A" are passed on to the observer.
Output:
Here, only the names that start with "A" (Alice, Andrew, Anna) are emitted and processed.
6. How .filter Helps in Android Applications
.filter Helps in Android ApplicationsIn an Android application, .filter can be incredibly useful when you need to work with a subset of data. Some practical use cases:
Filtering user input: You could filter out invalid inputs (like non-numeric characters) before performing calculations.
Filtering a list: For instance, when dealing with large datasets, you could filter items based on user preferences or search criteria (e.g., filtering products in a shopping app).
Filtering API responses: You could filter out irrelevant data from an API response before updating the UI with meaningful content.
7. Example: Filtering User Input in Android
Let’s consider an Android example where you have an app that takes user input, and you want to allow only numbers greater than 10.
Here’s a simple implementation:
Explanation:
The user enters a number, and when the button is clicked, the app checks if the number is greater than 10 using the
.filteroperator.If the number is greater than 10, it’s displayed on the screen. If not, it’s ignored.
Conclusion:
The .filter operator is a simple but powerful tool in RxJava that helps you work with a subset of data based on a condition. In Kotlin for Android, it can help in scenarios like filtering user input, refining data from lists, and managing large datasets efficiently. By using .filter, you can ensure that only the data you care about is passed down the stream and processed by the observer.
Last updated