es6/operator/find.js
import { Subscriber } from '../Subscriber';
/* tslint:enable:max-line-length */
/**
* 只发出源 Observable 所发出的值中第一个满足条件的值。
*
* <span class="informal">找到第一个通过测试的值并将其发出。</span>
*
* <img src="./img/find.png" width="100%">
*
* `find` 会查找源 Observable 中与 `predicate` 函数体现的指定条件匹配的第一项,然后
* 将其返回。不同于 {@link first},在 `find` 中 `predicate` 是必须的,而且如果没找到
* 有效的值的话也不会发出错误。
*
* @example <caption>找到并发出第一个点击 DIV 元素的事件</caption>
* var clicks = Rx.Observable.fromEvent(document, 'click');
* var result = clicks.find(ev => ev.target.tagName === 'DIV');
* result.subscribe(x => console.log(x));
*
* @see {@link filter}
* @see {@link first}
* @see {@link findIndex}
* @see {@link take}
*
* @param {function(value: T, index: number, source: Observable<T>): boolean} predicate
* 使用每项来调用的函数,用于测试是否符合条件。
* @param {any} [thisArg] 可选参数,用来决定 `predicate` 函数中的 `this` 的值。
* @return {Observable<T>} 符合条件的第一项的 Observable 。
* @method find
* @owner Observable
*/
export function find(predicate, thisArg) {
if (typeof predicate !== 'function') {
throw new TypeError('predicate is not a function');
}
return this.lift(new FindValueOperator(predicate, this, false, thisArg));
}
export class FindValueOperator {
constructor(predicate, source, yieldIndex, thisArg) {
this.predicate = predicate;
this.source = source;
this.yieldIndex = yieldIndex;
this.thisArg = thisArg;
}
call(observer, source) {
return source.subscribe(new FindValueSubscriber(observer, this.predicate, this.source, this.yieldIndex, this.thisArg));
}
}
/**
* We need this JSDoc comment for affecting ESDoc.
* @ignore
* @extends {Ignored}
*/
export class FindValueSubscriber extends Subscriber {
constructor(destination, predicate, source, yieldIndex, thisArg) {
super(destination);
this.predicate = predicate;
this.source = source;
this.yieldIndex = yieldIndex;
this.thisArg = thisArg;
this.index = 0;
}
notifyComplete(value) {
const destination = this.destination;
destination.next(value);
destination.complete();
}
_next(value) {
const { predicate, thisArg } = this;
const index = this.index++;
try {
const result = predicate.call(thisArg || this, value, index, this.source);
if (result) {
this.notifyComplete(this.yieldIndex ? index : value);
}
}
catch (err) {
this.destination.error(err);
}
}
_complete() {
this.notifyComplete(this.yieldIndex ? -1 : undefined);
}
}
//# sourceMappingURL=find.js.map