The take operator

The filter methods discussed previously enable us to select data. If we want to select the top 10 elements, for example, we can use the filter operator, with a predicate that has a counter. Alternatively, there is a take operator for this purpose. The operator takes a number and selects the specified number of elements, as follows:

fibonacciGenerator.take(10).subscribe(t -> {
    System.out.println(t);
});

The preceding code will select the first 10 values to form the Fibonacci generator.

Now, let's suppose that we want to select the last 10 elements. The takeLast operator is designed for this purpose. It also maintains a count and selects elements from the end of the series:

fibonacciGenerator.takeLast(10).subscribe(t -> { ...

Get Hands-On Reactive Programming with Reactor now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.