Why add a new operator and use lift rather than just using map in RxJava?

93 views Asked by At

I'm new to ReactiveX and trying to understand the lift operator. What I understand so far is that it's useful in allowing custom operators to be used in a reactive chains but also introduces overhead and can prevent operator fusion. I'm not quite getting how a custom operator and lift is different than just using map. For example, in the ReactiveX docs for "Implementing Your Own Operators", the below code is given

Observable foo = barObservable.ofType(Integer).map({it*2}).lift(new myOperator<T>()).map({"transformed by myOperator: " + it});
public class myOperator<T> implements Operator<T> {
  public myOperator( /* any necessary params here */ ) {
    /* any necessary initialization here */
  }

  @Override
  public Subscriber<? super T> call(final Subscriber<? super T> s) {
    return new Subscriber<t>(s) {
      @Override
      public void onCompleted() {
        /* add your own onCompleted behavior here, or just pass the completed notification through: */
        if(!s.isUnsubscribed()) {
          s.onCompleted();
        }
      }

      @Override
      public void onError(Throwable t) {
        /* add your own onError behavior here, or just pass the error notification through: */
        if(!s.isUnsubscribed()) {
          s.onError(t);
        }
      }

      @Override
      public void onNext(T item) {
        /* this example performs some sort of simple transformation on each incoming item and then passes it along */
        if(!s.isUnsubscribed()) {
          transformedItem = myOperatorTransformOperation(item);
          s.onNext(transformedItem);
        }
      }
    };
  }
}

Is this not equivalent to

Observable foo = barObservable.ofType(Integer).map({it*2}).map(myOperatorTransformOperation).map({"transformed by myOperator: " + it});

?

0

There are 0 answers