RxJava Operators With Examples

In this tutorial, we’ll discuss and implement the various operators that RxJava has. How each operator transforms the Observable sequences and what the subscriber sees? Let’s start!

Table of Contents

  • 1 RxJava Operators
    • 1.1 1. map and filter
    • 1.2 2. take, count and skip
    • 1.3 3. startWith,reduce, repeat, scan
    • 1.4 4. all, contains, elementAt
    • 1.5 5. distinct, toList, toSortedList
    • 1.6 6. concat, merge, zip
    • 1.7 7. debounce, delay

RxJava Operators

As we had seen in the first RxJava tutorial, Operators are something that acts on an Observable and passes the transformed data to the Subscribers. With multiple operators, each operator finishes its own task and then passes the transformed data to the next operator.

Create a new IntelliJ Java Project and add the RxJava dependency to get started. We’ll use functional programming and lambdas to make the code simpler and less verbose.

1. map and filter

map()

filter()

Using Map and Filter : To return the square of all the even numbers.

2. take, count and skip

take operator has three main variants. Let’s look at each of them.

  • take() passes the first n items emitted by the Observable.
  • takeFirst() emits the first item that meets the condition specified in the operator.
  • takeLast() prints the last n items. Just the opposite of take()
  • takeUntil() emits items until a second observable doesn’t start emitting values. Alternatively, it can be used for conditions as well.
  • takeWhile() emits items as long as a condition is true. It ignores the remaining.

The takeFirst() function prints the first value whose square is greater than 1000.
The takeUntil() operator is like a do-while loop. It first prints the statement before checking for the condition for the next iteration.

As the name says, count() returns the number of values that reach the subscriber.

Passing null as one of the values would cause a runtime crash in the above case. Hence we need to specify the action for onError()

skip operator has a few variants that are described and implemented below

  • skip() ignores the first n values.
  • skipLast() ignored the last n values
  • skipWhile() ignores all the values until a specific condition is met. It emits all the remainder of values.
  • skipUntil() ignores all the values until another observable starts emitting. We’ll look at this later

skip is somewhat the opposite of take.

skip is the ideal operator to use when avoiding null values.

3. startWith,reduce, repeat, scan

startWith() appends the given element at the start of the emission.

reduce() operator acts as an accumulator. It adds a the next value to previously added values.
Finally prints the accumulated value for the subscriber.

In the above code, for the first emission, integer is 1 integer2 is 2, for the second emission, 3 and 3 respectively and so on.

reduce operator is useful for calculating the sum, appending strings etc.
The following code finds the length of the concatenated strings.

repeat operator repeats the emission twice.

scan operator unlike reduce, prints the accumulator value incrementally

4. all, contains, elementAt

The all() operator checks whether each value meets the condition. It returns a true/false.

contains(): It checks if the value mentioned exists in the Observable lot.

elementAt() : It prints the value present at the given index among the list of emitted values.

5. distinct, toList, toSortedList

distinct() operator eliminates duplicate values.

toList and toSortedList are used to convert the emission into another observable that is of the type list.
toSortedList sorts the emission in ascending order.
We can also set our own comparator to sort.

In the above code, the third observable sorts the values in descending order.

6. concat, merge, zip

concat is used to concatenate observables without interleaving them.
merge is used to concatenate observables by interleaving them
That means that in concat the new observable would contain the first followed by the second.
In merge they can be mixed, depending on when they arrive.

Note: We need to add a sleep to prevent early exit of the main function.
In the concat() method, until the first observable isn’t done it won’t move to the second.
So in the above code, the second doesn’t get printed since the first observable prints its quota in the 5 seconds.
Let’s set a limit on the first using take.

merge two observables

As you can see merge interleaves them. But it doesn’t guarantee the sequence of emission.

merge and concat above work on Observables only.
To make them work as operators we need to use mergeWith and concatWith

Use concatWith in the above code to get the relevant operator for concat.

zip is used to pair each emission from each of the observables. Each observable would wait for the others to emit the current value and then each of the values is available for you in a function.
zip is useful to concatenate different types.

In the above code, the first observable emits an integer every second. The map operator converts the integer to the relevant character using the ASCII code and returns it as a string.
The second observable emits an integer every two seconds. So the first observable needs to wait for this.

Try implementing the zipWith operator yourself. It’s analogous to concatWith and mergeWith.

7. debounce, delay

A debounce operator only emits an item from an Observable if a particular timespan has passed without it emitting another item. This operator is really useful in places like EditText in a SearchView in Android.
Typically entering anything, the search view would call a backend API with the current text. Using the debounce operator saves the immediate call. It gives the user a time to assess the text they’ve entered and whether they’re looking to modify it. Only after the certain timespan is passed the backend API would be called!

The last element is printed in the cases like above since there is nothing left and the debounce operator emits the value after the delay.

The delay operator delays the start of emission of values from the Observable by a certain time.

In the above code, nothing happens since our main function would return after 4 seconds thereby preventing the emission that was to occur after 5 seconds.

This brings an end to this tutorial. We’ve covered some major operators. You can download the RxJavaOperators Project source code from the link below.

By admin

Leave a Reply

%d bloggers like this: