ITZone

Common operators used in RxJava

As learn in part 1 about Rx in this article, I will focus on the operators used in Rx java

— Creating Observables

1.just()

As the name of the function, the operator emits only the same values provided in the arguments.


VD : Observable.just(1, 2, 3, 4, 5)

Here, our observable with just operator has been applied. So the observable will emit between 1 and 5 integers.

— Filtering Operators:

As the name suggests the filter operator, filters the items emitted by an Observable. Using filter() we can decide whether to emit the object or not based on some condition.

2. skip():
skip(n) will discard the first n items emitted by an Observable and emit data after n elements. So skip(2) will skip playing the first 2 elements and start from emitting the 3rd element.

So for our example, if we apply skip(2) operator, it will emit only 3, 4 and 5 integers.

3. take(): take() is the opposite of the skip() operator. take(n) will emit only the first n data elements and skip all data elements after the n emitted elements.

— Combining Operators:

1. merge():
The merge() operator combines multiple Observables into one by merging the elements emitted by the Observables. The merge() operator can interleave outputs because it emits data from both Observables. simultaneously as soon as data is available to play.

2. zip():
zip() combines the emission of multiple operators together through a specified function and emits single entries for each combination based on the result of this function.

Here is an example where you can combine strings and integer data streams into a ZipObject (custom class) and emit them as the final data stream.

— Mathematical and Aggregate Operators

1. concat(): The Concat operator concatenates the output of multiple Observables so that they behave like a single Observable.

Let’s say you have two observables. Observable1 emits integers from 1 to 5 respectively and an Observable2 emits integers from 6 to 10. If we combine them, Observable1 will emit from 1 to 5 and Observable2 will emit data from 6 to 10 at the same time. The concat() operator will merge both the data stream and emit data from Observable1 and then emit data from Observable2. Below is an explanatory diagram.

References:

Share the news now