rxjs里concatMap operators的用法

时间:2022-07-28
本文章向大家介绍rxjs里concatMap operators的用法,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Projects each source value to an Observable which is merged in the output Observable, in a serialized fashion waiting for each one to complete before merging the next.

将source Observable里的每个元素施加一个projection函数,这个projection函数返回一个新的Observable,然后将所有这些Observable flatten成另一个Observable.

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 (so-called “inner”) Observable. Each new inner Observable is concatenated with the previous inner Observable.

例子:

const clicks = fromEvent(document, 'click');
    const ioe = interval(1000);
    const mapfn = take(4);
    const comp = ioe.pipe(mapfn);
    const fn = ev => comp;
    const result = clicks.pipe( concatMap(fn));
    result.subscribe(x => console.log('diablo: ' +x));

ioe是Observable:

mapfn是OperatorFunction:

comp是一个新的Observable:

fn函数接收任意类型的输入变量,返回一个新的Observable:

测试结果:每点击屏幕一次,顺序打印0~4:

concatMap语义:每点击一次,从interval Observable中拿出4个元素出来,生成4个新的Observable,然后连接在一起。