Exploring RxJava in Android — Mathematical and Aggregate Operators
This article is part of RxJava Introduction series. You can checkout the entire series here:
- RxJava Introduction and Operators for creating Observables
- RxJava Operators: Operators for Transforming Observables
- RxJava Operators: Operators for Filtering Observables
- RxJava Operators: Operators for Combining Observables
- RxJava Operators: Utility Operators
- RxJava Operators: Conditional and Boolean Operators
- RxJava Operators: Mathematical and Aggregate Operators — You are here
- RxJava: Different types of Observables
- RxJava: Different types of Subjects
Mathematical and Aggregate Operators
Mathematical Observables require extra dependency. Add the following dependency inside the build.gradle file and sync gradle.
implementation 'com.github.akarnokd:rxjava2-extensions:0.20.0'
Now, let’s take take a look at the following mathematical operators.
Average
This operator calculates the average of the items emitted by an Observable and emits this average.
Sample Implementation: The below code demonstrates the use of average()
operator.
Output
Average: 3.0
Count
This operator counts the number of items emitted by the source Observable and emit only this value.
Sample Implementation: The below code demonstrates the use of count()
operator.
Output
Count: 5
Max
This operator determines the maximum-valued item emitted by an Observable sequence and emits that item.
Sample Implementation: The below code demonstrates the use of max()
operator.
Output
Max value: 5
Min
This operator determines the minimum-valued item emitted by an Observable sequence and emits that item.
Sample Implementation: The below code demonstrates the use of min()
operator.
Output
Max value: 1
Reduce
This operator applies a function to each item emitted by an Observable, sequentially, and emit the final value. First it applies a function to first item, takes the result and feeds back to same function on second item. This process continuous until the last emission. Once all the items are over, it emits the final result.
Sample Implementation: The below code demonstrates the use of reduce()
operator.
Output
Product of numbers from 1, 2, 3, 4, 5: 120
Sum
This operator calculates the sum of numbers emitted by an Observable and emits this sum.
Sample Implementation: The below code demonstrates the use of sum()
operator.
Output
Sum: 15
That’s it guys! This is part seven of the series on RxJava. I hope you enjoyed this article and found it useful, if so please hit the Clap button. Let me know your thoughts in the comments section.
Happy coding!