Ok so just to learn RxJS better, decided to try my hand at creating a custom Rx operator.
So here is a simple one that works fine:
Rx.Observable.prototype.multiply = function (input) {
const source = this;
return Rx.Observable.create(function (obs) {
return source.subscribe(function(val){
obs.next(input*val);
});
});
};
and we can use it like so:
const obs = Rx.Observable.interval(1000)
.multiply(4)
.forEach(function (v) {
console.log(v);
});
however, what if we get something a little more complicated, for example if our operator takes a function instead of a static value.
Rx.Observable.prototype.handleFn = function (fn) {
const source = this;
return Rx.Observable.create(function (obs) {
return source.subscribe(function(val){
obs.next(fn.call(obs,val));
});
});
};
the above is all good and well, but what if we need to handle an Rx.Observable that gets returned from the input function, something like this:
const obs = Rx.Observable.interval(1000)
.handleFn(function(){
return Rx.Observable.timer(399);
})
.forEach(function (v) {
console.log(v);
});
is there some sort of Promise.resolve() but for Observables so that I can resolve the result of Rx.Observable.timer()? Will check out the source code for Rx.Observable.prototype.flatMap
etc.!
You could use a
.mergeAll()
, like this:see live JSBin here.
Option 2: Instead of
mergeAll
, you could also do the following:Additional Note: If you want to see how this is properly implemented, take a look(as you already mentioned yourself) at the source of
flatMap, switchMap, concatMap
.