concat

signature: concat(observables: ...*): Observable

Subscribe to observables in order as previous completes, emit values.


:bulb: You can think of concat like a line at a ATM, the next transaction (subscription) cannot start until the previous completes!

:bulb: This operator can be used as either a static or instance method!

:bulb: If throughput, not order, is not a primary concern, try merge instead!


Examples

( example tests )

Example 1: concat 2 basic observables

( jsBin | jsFiddle )

import { concat } from 'rxjs/operators';
import { of } from 'rxjs/observable/of';

//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

( jsBin | jsFiddle )

import { of } from 'rxjs/observable/of';
import { concat } from 'rxjs/observable/concat';

//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('Example: static', val));
Example 3: concat with delayed source

( jsBin | jsFiddle )

import { delay, concat } from 'rxjs/operators';
import { of } from 'rxjs/observable/of';

//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

( jsBin | jsFiddle )

import { interval } from 'rxjs/observable/interval';
import { of } from 'rxjs/observable/of';
import { concat } from 'rxjs/observable/concat';

//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


:file_folder: Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/internal/patching/operator/concat.ts

results matching ""

    No results matching ""