Observable类中主要方法分析,一般从最简单的创建Observable,并订阅相应的Observable的例子开始分析整个Observable的大概流程,
如例子:
1 2 3 4 5 6 7
| const o$ = new Observable(subscriber => { subscriber.next(1); subscriber.next(2); });
const o$.subscribe(x => console.log(x));
|
下面开始看源码:
1 2 3 4 5 6 7 8 9 10 11 12
|
constructor(subscribe?: (this: Observable<T>, subscriber: Subscriber<T>) => TeardownLogic)
} static create: Function = <T>(subscribe?: (subscriber: Subscriber<T>) => TeardownLogic) =>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
subscribe(observerOrNext?: PartialObserver<T> | ((value: T) => void), error?: (error: any) => void, complete?: () => void): Subscription {
const { operator } = this; const sink = toSubscriber(observerOrNext, error, complete);
if (operator) { sink.add(operator.call(sink, this.source)); } else { sink.add( this.source || (config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ? this._subscribe(sink) : this._trySubscribe(sink) ); } if (config.useDeprecatedSynchronousErrorHandling) { if (sink.syncErrorThrowable) { sink.syncErrorThrowable = false; if (sink.syncErrorThrown) { throw sink.syncErrorValue; } } }
return sink; }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
_subscribe(subscriber: Subscriber<any>): TeardownLogic { const { source } = this; return source && source.subscribe(subscriber); }
_trySubscribe(sink: Subscriber<T>): TeardownLogic { try { return this._subscribe(sink); } catch (err) { if (config.useDeprecatedSynchronousErrorHandling) { sink.syncErrorThrown = true; sink.syncErrorValue = err; } if (canReportError(sink)) { sink.error(err); } else { console.warn(err); } } }
|
创建Observable的时候,函数并没有执行,只是将函数赋值给个变量,当订阅者开始订阅subscribe的时候才开始执行函数,所以Observable是惰性的,这个特性像函数一样,
同时订阅者也不关心什么时候返回值,我把参数callback传给你了,当你return值的时候,调用callback即可,和promise差不多,所以适合做异步运算。