Javascript Promise.resolve()但用于可观察对象(RxJS5)
为了更好地学习RxJS,我决定尝试创建一个自定义Rx操作符 因此,这里有一个简单的方法可以很好地工作:Javascript Promise.resolve()但用于可观察对象(RxJS5),javascript,node.js,rxjs5,angular2-observables,Javascript,Node.js,Rxjs5,Angular2 Observables,为了更好地学习RxJS,我决定尝试创建一个自定义Rx操作符 因此,这里有一个简单的方法可以很好地工作: Rx.Observable.prototype.multiply = function (input) { const source = this; return Rx.Observable.create(function (obs) { return source.subscribe(function(val){ obs.next
Rx.Observable.prototype.multiply = function (input) {
const source = this;
return Rx.Observable.create(function (obs) {
return source.subscribe(function(val){
obs.next(input*val);
});
});
};
我们可以这样使用它:
const obs = Rx.Observable.interval(1000)
.multiply(4)
.forEach(function (v) {
console.log(v);
});
然而,如果我们得到一些更复杂的东西,例如,如果我们的运算符采用函数而不是静态值,该怎么办
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));
});
});
};
以上都很好,但是如果我们需要处理从输入函数返回的Rx.Observable,该怎么办
const obs = Rx.Observable.interval(1000)
.handleFn(function(){
return Rx.Observable.timer(399);
})
.forEach(function (v) {
console.log(v);
});
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));
});
});
};
const obs = Rx.Observable.interval(1000)
.handleFn(function(){
return Rx.Observable.timer(150).mapTo(Math.random());
})
.mergeAll();
obs.subscribe(x => console.log(x));
是否有某种承诺.resolve()但对于Observable,以便我可以解析Rx.Observable.timer()的结果?将检查
Rx.Observable.prototype.flatMap
等的源代码 您可以使用.mergeAll()
,如下所示:
const obs = Rx.Observable.interval(1000)
.handleFn(function(){
return Rx.Observable.timer(399);
})
.forEach(function (v) {
console.log(v);
});
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));
});
});
};
const obs = Rx.Observable.interval(1000)
.handleFn(function(){
return Rx.Observable.timer(150).mapTo(Math.random());
})
.mergeAll();
obs.subscribe(x => console.log(x));
见现场JSBin
选项2: 除了
mergeAll
,您还可以执行以下操作:
Rx.Observable.prototype.handleFn = function (fn) {
const source = this;
return Rx.Observable.create(function (obs) {
return source.subscribe(function(val){
fn.call(obs,val).subscribe(x => obs.next(x));
});
});
};
附加说明:如果您想了解这是如何正确实现的,请查看
flatMap、switchMap、concatMap
的源代码(正如您已经提到的),看看源代码,它是用TypeScript编写的(对它们很好)。但我不知道TS,所以我把它传送到了ES5。事实证明flatMap和mergeMap应该是等效的运算符,并且mergeMap是源中唯一的运算符,在这里它被传输:
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var subscribeToResult_1 = require("../util/subscribeToResult");
var OuterSubscriber_1 = require("../OuterSubscriber");
/* tslint:disable:max-line-length */
/**
* Projects each source value to an Observable which is merged in the output
* Observable.
*
* <span class="informal">Maps each value to an Observable, then flattens all of
* these inner Observables using {@link mergeAll}.</span>
*
* <img src="./img/mergeMap.png" width="100%">
*
* Returns an Observable that emits items based on applying a function that you
* supply to each item emitted by the source Observable, where that function
* returns an Observable, and then merging those resulting Observables and
* emitting the results of this merger.
*
* @example <caption>Map and flatten each letter to an Observable ticking every 1 second</caption>
* var letters = Rx.Observable.of('a', 'b', 'c');
* var result = letters.mergeMap(x =>
* Rx.Observable.interval(1000).map(i => x+i)
* );
* result.subscribe(x => console.log(x));
*
* // Results in the following:
* // a0
* // b0
* // c0
* // a1
* // b1
* // c1
* // continues to list a,b,c with respective ascending integers
*
* @see {@link concatMap}
* @see {@link exhaustMap}
* @see {@link merge}
* @see {@link mergeAll}
* @see {@link mergeMapTo}
* @see {@link mergeScan}
* @see {@link switchMap}
*
* @param {function(value: T, ?index: number): Observable} project A function
* that, when applied to an item emitted by the source Observable, returns an
* Observable.
* @param {function(outerValue: T, innerValue: I, outerIndex: number, innerIndex: number): any} [resultSelector]
* A function to produce the value on the output Observable based on the values
* and the indices of the source (outer) emission and the inner Observable
* emission. The arguments passed to this function are:
* - `outerValue`: the value that came from the source
* - `innerValue`: the value that came from the projected Observable
* - `outerIndex`: the "index" of the value that came from the source
* - `innerIndex`: the "index" of the value from the projected Observable
* @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input
* Observables being subscribed to concurrently.
* @return {Observable} An Observable that emits the result of applying the
* projection function (and the optional `resultSelector`) to each item emitted
* by the source Observable and merging the results of the Observables obtained
* from this transformation.
* @method mergeMap
* @owner Observable
*/
function mergeMap(project, resultSelector, concurrent) {
if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
if (typeof resultSelector === 'number') {
concurrent = resultSelector;
resultSelector = null;
}
return this.lift(new MergeMapOperator(project, resultSelector, concurrent));
}
exports.mergeMap = mergeMap;
var MergeMapOperator = (function () {
function MergeMapOperator(project, resultSelector, concurrent) {
if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
this.project = project;
this.resultSelector = resultSelector;
this.concurrent = concurrent;
}
MergeMapOperator.prototype.call = function (observer, source) {
return source.subscribe(new MergeMapSubscriber(observer, this.project, this.resultSelector, this.concurrent));
};
return MergeMapOperator;
}());
exports.MergeMapOperator = MergeMapOperator;
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
var MergeMapSubscriber = (function (_super) {
__extends(MergeMapSubscriber, _super);
function MergeMapSubscriber(destination, project, resultSelector, concurrent) {
if (concurrent === void 0) { concurrent = Number.POSITIVE_INFINITY; }
var _this = _super.call(this, destination) || this;
_this.project = project;
_this.resultSelector = resultSelector;
_this.concurrent = concurrent;
_this.hasCompleted = false;
_this.buffer = [];
_this.active = 0;
_this.index = 0;
return _this;
}
MergeMapSubscriber.prototype._next = function (value) {
if (this.active < this.concurrent) {
this._tryNext(value);
}
else {
this.buffer.push(value);
}
};
MergeMapSubscriber.prototype._tryNext = function (value) {
var result;
var index = this.index++;
try {
result = this.project(value, index);
}
catch (err) {
this.destination.error(err);
return;
}
this.active++;
this._innerSub(result, value, index);
};
MergeMapSubscriber.prototype._innerSub = function (ish, value, index) {
this.add(subscribeToResult_1.subscribeToResult(this, ish, value, index));
};
MergeMapSubscriber.prototype._complete = function () {
this.hasCompleted = true;
if (this.active === 0 && this.buffer.length === 0) {
this.destination.complete();
}
};
MergeMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
if (this.resultSelector) {
this._notifyResultSelector(outerValue, innerValue, outerIndex, innerIndex);
}
else {
this.destination.next(innerValue);
}
};
MergeMapSubscriber.prototype._notifyResultSelector = function (outerValue, innerValue, outerIndex, innerIndex) {
var result;
try {
result = this.resultSelector(outerValue, innerValue, outerIndex, innerIndex);
}
catch (err) {
this.destination.error(err);
return;
}
this.destination.next(result);
};
MergeMapSubscriber.prototype.notifyComplete = function (innerSub) {
var buffer = this.buffer;
this.remove(innerSub);
this.active--;
if (buffer.length > 0) {
this._next(buffer.shift());
}
else if (this.active === 0 && this.hasCompleted) {
this.destination.complete();
}
};
return MergeMapSubscriber;
}(OuterSubscriber_1.OuterSubscriber));
exports.MergeMapSubscriber = MergeMapSubscriber;
//# sourceMappingURL=mergeMap.js.map
“严格使用”;
var u extends=(this&&this.u extends)| |函数(d,b){
如果(b.hasOwnProperty(p))d[p]=b[p];
函数{this.constructor=d;}
d、 prototype=b==null?对象。创建(b):(_uu.prototype=b.prototype,new_u());
};
var subscribeToResult_1=require(“../util/subscribeToResult”);
var OuterSubscriber_1=require(“../OuterSubscriber”);
/*tslint:禁用:最大行长度*/
/**
*将每个源值投影到合并到输出中的可观察值
*可见的。
*
*将每个值映射到一个可观察值,然后展平所有值
*这些内部观察值使用{@link mergeAll}。
*
*
*
*返回一个可观测项,该可观测项基于应用所需的函数来发射项
*向可观察到的源发出的每个项目提供,其中
*返回一个可观测值,然后合并这些结果可观测值和
*公布这次合并的结果。
*
*@example映射每个字母,并每1秒将其展平为一个可观察到的滴答声
*var字母=Rx.可观察的('a','b','c');
*var result=letters.mergeMap(x=>
*Rx.可观测间隔(1000).映射(i=>x+i)
* );
*subscribe(x=>console.log(x));
*
*//结果如下:
*//a0
*//b0
*//c0
*//a1
*//b1
*//c1
*//继续列出a、b、c以及相应的升序整数
*
*@见{@link concatMap}
*@见{@link defaustmap}
*@请参阅{@link merge}
*@请参阅{@link mergeAll}
*@请参阅{@link mergeMapTo}
*@请参阅{@link mergeScan}
*@请参阅{@link switchMap}
*
*@param{function(value:T,?index:number):可观察的}投射一个函数
*当应用于源可观测项发出的项时,返回
*可见的。
*@param{function(outerValue:T,innerValue:I,outerIndex:number,innerIndex:number):any}[resultSelector]
*一种函数,用于根据这些值在输出上生成可观察的值
*以及源(外部)发射和内部可观测的指数
*排放。传递给此函数的参数为:
*-`outerValue`:来自源的值
*-`innerValue`:来自投影可观察对象的值
*-`outerIndex`:来自源的值的“索引”
*-`innerIndex`:预测可观测值的“索引”
*@param{number}[concurrent=number.POSITIVE_无穷大]最大输入数
*同时订阅的可观测数据。
*@return{Observable}发出应用
*将函数(以及可选的“resultSelector”)投影到发出的每个项目
*通过源可观测值并合并获得的可观测值的结果
*从这个转变。
*@methodmergemap
*@可观察到的所有者
*/
函数合并映射(项目、结果选择器、并发){
如果(concurrent==void 0){concurrent=Number.POSITIVE_无穷大;}
如果(结果选择器的类型=='number'){
并发=结果选择器;
resultSelector=null;
}
返回此.lift(新的MergeMapOperator(项目、结果选择器、并发));
}
exports.mergeMap=mergeMap;
var MergeMapOperator=(函数(){
函数MergeMapOperator(项目、结果选择器、并发){
如果(concurrent==void 0){concurrent=Number.POSITIVE_无穷大;}
this.project=项目;
this.resultSelector=resultSelector;
this.concurrent=concurrent;
}
MergeMapOperator.prototype.call=函数(观察者,源){
返回source.subscribe(新的MergeMapSubscriber(observer,this.project,this.resultSelector,this.concurrent));
};
返回合并映射运算符;
}());
exports.MergeMapOperator=MergeMapOperator;
/**
*我们需要这个JSDoc注释来影响ESDoc。
*@忽略
*@extends{Ignored}
*/
var MergeMapSubscriber=(函数(_super){
__扩展(MergeMapSubscriber,_super);
函数MergeMapSubscriber(目标、项目、结果选择器、并发){
如果(concurrent==void 0){concurrent=Number.POSITIVE_无穷大;}
var _this=_super.call(this,destination)| this;
_this.project=项目;
_this.resultSelector=resultSelector;
_this.concurrent=concurrent;
_this.hasCompleted=false;
_this.buffer=[];
_此参数为0;
_该指数=0;
把这个还给你;
}
MergeMapSubscriber.prototype.\u next=函数(值){
if(this.active