rxjs里concat operators的用法

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

concat joins multiple Observables together, by subscribing to them one at a time and merging their results into the output Observable. You can pass either an array of Observables, or put them directly as arguments. Passing an empty array will result in Observable that completes immediately.

concat接受多个Observable作为参数,在同一个时间点subscribe这些Observable,将其结果合并到一个新的output Observable中去。

concat will subscribe to first input Observable and emit all its values, without changing or affecting them in any way. When that Observable completes, it will subscribe to then next Observable passed and, again, emit its values. This will be repeated, until the operator runs out of Observables. When last input Observable completes, concat will complete as well. At any given moment only one Observable passed to operator emits values. If you would like to emit values from passed Observables concurrently, check out merge instead, especially with optional concurrent parameter. As a matter of fact, concat is an equivalent of merge operator with concurrent parameter set to 1.

concat会subscribe参数里第一个input Observable,emit数据,然后串行地处理下一个Observable,直到conat参数列表里所有Observable都处理完。如果想使传入concat的所有Observable都同时并发地emit value,使用merge.

concat 等价于merge operator以concurrent参数为1的方式去运行。

看个例子:

import { concat, interval, range } from 'rxjs';
import { take } from 'rxjs/operators';

const timer = interval(1000).pipe(take(4));
const sequence = range(1, 10);
const result = concat(timer, sequence);
result.subscribe(x => console.log(x));

// results in:
// 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10

测试结果:

先以每秒的间隔,慢慢显示出0,1,2,3一共4个数(来自interval Observable),然后一秒之内打印1~10(来自range Observable):

const timer1 = interval(1000).pipe(take(10));
const timer2 = interval(2000).pipe(take(6));
const timer3 = interval(500).pipe(take(10));
 
const result = concat(timer1, timer2, timer3);
result.subscribe(x => console.log('Jerry: ' + x));

以1秒的时间间隔打印0~9,以2秒的时间间隔打印0~5,以0.5秒的时间间隔打印0~9: