Book Image

Learning Reactive Programming with Java 8

By : Nickolay Tzvetinov
Book Image

Learning Reactive Programming with Java 8

By: Nickolay Tzvetinov

Overview of this book

Table of Contents (15 chapters)
Learning Reactive Programming with Java 8
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Creating custom operators with lift


After learning about and using so many various operators, we are ready to write our own operators. The Observable class has an operator called lift. It receives an instance of the Operator interface. This interface is just an empty one that extends the Func1<Subscriber<? super R>, Subscriber<? super T>> interface. This means that we can pass even lambdas as operators.

The best way of learning how to use the lift operator is to write an example of it. Let's create an operator that adds a sequential index to every item emitted (of course, this is doable without a dedicated operator). This way, we will be able to produce indexed items. For this purpose, we need a class that stores an item and its index. Let's create a more general class called Pair:

public class Pair<L, R> {
  final L left;
  final R right;
  
public Pair(L left, R right) {
    this.left = left;
    this.right = right;
  }

  public L getLeft() {
    return left;
  ...