0

I'm trying to subclass the RxJS Observable class as described here by subclassing Observable and overriding the lift method.

This works for any operators I add to the prototype, but whenever I try to instantiate a new Observable of my subclass (e.g. using MyObservable.from([1, 2, 3]), I get an Observable of the parent class.

How do I subclass Observable correctly, so that using Observable.return / Observable.from / works as expected? jsbin

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

  customOperator() {
    return this.map(arguments)
  }
}


// instantiating an observable with **MyObservable**.from
var observable = MyObservable.from([1, 2, 3]);
console.log('instance of Rx.Observable: ' + observable instanceof Rx.Observable);


// this works as map is defined on RxObservable
observable
  .map(value => console.log('standard ' + value)) 
  .subscribe();


// this doesn't work. customOperator is only defined on MyObservable
// and MyObservable.from([1, 2, 3]) returns an Rx.Observable instance
observable
  .customOperator(value => console.log('custom ' + value)) 
  .subscribe();    
Niklas Fasching
  • 1,326
  • 11
  • 15

2 Answers2

1

I think you cannot do that. You might need to do some monkey patching and do something like

Observable.prototype.customOperator = /*blabla*/

this way everything subclassing Observable will have customOperator.

Andrea Baccega
  • 27,211
  • 13
  • 45
  • 46
0

I opened an issue for this here and it turns out there's currently no clean solution to this.

Once this PR providing the let operator is merged the cleanest solution will be to wrap the original observable:

class MyObservable extends Observable {
  constructor(source) {
    this.source = source;
  }

  lift(operator) {
    const observable = new MyObservable(); //<-- important part here
    observable.source = this;
    observable.operator = operator;
    return observable;
  }
}


Observable.of(42)
  .let(o => new MyObservable(o))
Niklas Fasching
  • 1,326
  • 11
  • 15