
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):