concat
signature: concat(observables: ...*): Observable
Subscribe to observables in order as previous completes, emit values.
You can think of concat like a line at a ATM, the next transaction (subscription) cannot start until the previous completes!
This operator can be used as either a static or instance method!
If throughput, not order, is a primary concern, try merge instead!
Examples
( example tests )
Example 1: concat 2 basic observables
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+
import { concat } from 'rxjs/operators';
import { of } from 'rxjs';
//emits 1,2,3
const sourceOne = of(1, 2, 3);
//emits 4,5,6
const sourceTwo = of(4, 5, 6);
//emit values from sourceOne, when complete, subscribe to sourceTwo
const example = sourceOne.pipe(concat(sourceTwo));
//output: 1,2,3,4,5,6
const subscribe = example.subscribe(val =>
console.log('Example: Basic concat:', val)
);
Example 2: concat as static method
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+
import { of, concat } from 'rxjs';
//emits 1,2,3
const sourceOne = of(1, 2, 3);
//emits 4,5,6
const sourceTwo = of(4, 5, 6);
//used as static
const example = concat(sourceOne, sourceTwo);
//output: 1,2,3,4,5,6
const subscribe = example.subscribe(val => console.log(val));
Example 3: concat with delayed source
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+
import { delay, concat } from 'rxjs/operators';
import { of } from 'rxjs';
//emits 1,2,3
const sourceOne = of(1, 2, 3);
//emits 4,5,6
const sourceTwo = of(4, 5, 6);
//delay 3 seconds then emit
const sourceThree = sourceOne.pipe(delay(3000));
//sourceTwo waits on sourceOne to complete before subscribing
const example = sourceThree.pipe(concat(sourceTwo));
//output: 1,2,3,4,5,6
const subscribe = example.subscribe(val =>
console.log('Example: Delayed source one:', val)
);
Example 4: concat with source that does not complete
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+
import { interval, of, concat } from 'rxjs';
//when source never completes, the subsequent observables never runs
const source = concat(interval(1000), of('This', 'Never', 'Runs'));
//outputs: 0,1,2,3,4....
const subscribe = source.subscribe(val =>
console.log(
'Example: Source never completes, second observable never runs:',
val
)
);
Additional Resources
- concat - Official docs
- Combination operator: concat, startWith - André Staltz
Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/concat.ts