The aggregate operators and the BlockingObservable class

Aggregate operators produce the Observable instances, which emit only one item and complete. This item is composed or is computed using all the items emitted by the source Observable instance. In this section, we'll talk about only two of them. For more detailed information, refer to https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators.

The first of these operators is the count() or countLong() method. It emits the number of the items emitted by the source Observable instance. For example:

Observable
  .range(10, 100)
  .count()
  .subscribe(System.out::println);

This will print 100.

The other one is the toList() or toSortedList() method, which emits a list variable (that can be sorted) containing all of the items emitted by the source Observable instance and completes.

List<Integer> list = Observable
  .range(5, 15)
  .toList()
  .subscribe(System.out::println);

This will output the following:

[5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

All these methods, combined with the toBlocking() method, work well together. For example, if we want to retrieve the list of all the items emitted by the source Observable instance, we can do it like this:

List<Integer> single = Observable
  .range(5, 15)
  .toList()
  .toBlocking().single();

And we can use this collection of items however we want: for example, for testing.

Tip

The aggregate operators include a collect() operator as well, which can be used for generating Observable instances and emitting arbitrary collections, say Set() operator, for example.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.187.210