Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rx js understanding the lift method

I want to create a new operator and I find in the documentation that one of the ways is to do something like this:

class MyObservable extends Observable {
  lift(operator) {
    const observable = new MyObservable()
    observable.source = this;
    observable.operator = operator;
    return observable;
  }

  // put it here .. or ..
  customOperator() {
    /* do things and return an Observable */
  }
}

// ... put it here...
MyObservable.prototype.mySimpleOperator = mySimpleOperator;

I don't understand what is the lift method and what is going on here, can someone help, please?

like image 212
ng2user Avatar asked May 04 '17 05:05

ng2user


1 Answers

lift is used all the time internally in RxJS 5. The principle of lift is that you prepare a new Observable that upon subscribe will forward the events in the way the operator defines. There is a good video about it by Paul Taylor (https://youtu.be/QhjALubBQPg?t=19m). Lift is a very fundamental building block.

Instead of creating a new class - extending Observable - you could also just create the Operator itself. Users of the operator can then call it by writing:

Observable.of(1, 2, 3)
  .lift(new MyCustomOperator)
  .subscribe()

This means no-one has to learn that yet another operator is available in the Observable API, but instead sees that it is something defined elsewhere.

Ideally you could write

someObservable::myCustomOperator();

but unfortunately the bind-operator might be long away / never gonna happen, so the .lift(operator) seems like the most explicit / clean way.

like image 200
Herman Avatar answered Nov 04 '22 11:11

Herman