Skip to content

Latest commit

 

History

History
92 lines (68 loc) · 3.12 KB

concat.md

File metadata and controls

92 lines (68 loc) · 3.12 KB

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 order is not a primary concern, try merge instead!


Examples

( example tests )

Example 1: concat 2 basic observables

( jsBin | jsFiddle )

//emits 1,2,3
const sourceOne = Rx.Observable.of(1,2,3);
//emits 4,5,6
const sourceTwo = Rx.Observable.of(4,5,6);
//emit values from sourceOne, when complete, subscribe to sourceTwo
const example = sourceOne.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 )

//emits 1,2,3
const sourceOne = Rx.Observable.of(1,2,3);
//emits 4,5,6
const sourceTwo = Rx.Observable.of(4,5,6);

//used as static
const example = Rx.Observable.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 )

//emits 1,2,3
const sourceOne = Rx.Observable.of(1,2,3);
//emits 4,5,6
const sourceTwo = Rx.Observable.of(4,5,6);

//delay 3 seconds then emit
const sourceThree = sourceOne.delay(3000);
//sourceTwo waits on sourceOne to complete before subscribing
const example = sourceThree.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 )

//when source never completes, the subsequent observables never runs
const source = Rx.Observable
  .concat(
  	Rx.Observable.interval(1000),
  	Rx.Observable.of('This','Never','Runs')  
  )
//outputs: 1,2,3,4....
const subscribe = source.subscribe(val => console.log('Example: Source never completes, second observable never runs:', val));

Additional Resources


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