rxjs里的Observable对象的pipe方法

源代码:

import { of } from 'rxjs';
import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators';
import { tap } from 'rxjs/operators';

@Injectable()
export class JerrySandBoxService{
    name = 'Jerry';
    print(){
        const observable = of(1, 2, 3);
        const newObservable = observable.pipe(
            tap(num => console.log(num)),
            map(num => 'hello world: ' + num)
        );
        newObservable.subscribe(data => console.log(data));
    }
}

执行pipe之前先执行map函数:

map返回一个新的函数:

然后执行pipe函数:…operations变长参数,包含tap和map两个操作。


pipeFromArray的实现借助了JavaScript的closure闭包:

到目前为止,我们传入的tap和map里的箭头函数都未执行,直到subscribe方法的调用:

此时对于数组里的1,2,3,先执行管道里的tap和map操作,再把map操作的输出,作为输入去执行subscribe里指定的回调:

要获取更多Jerry的原创文章,请关注公众号"汪子熙":

猜你喜欢

转载自blog.csdn.net/i042416/article/details/108600630