merge

signature: merge(input: Observable): Observable

Turn multiple observables into a single observable.


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

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


merge - 图3

Examples

Example 1: merging multiple observables, static method

( StackBlitz |
jsBin |
jsFiddle )

  1. import { mapTo } from 'rxjs/operators';
  2. import { interval } from 'rxjs/observable/interval';
  3. import { merge } from 'rxjs/observable/merge';
  4. //emit every 2.5 seconds
  5. const first = interval(2500);
  6. //emit every 2 seconds
  7. const second = interval(2000);
  8. //emit every 1.5 seconds
  9. const third = interval(1500);
  10. //emit every 1 second
  11. const fourth = interval(1000);
  12. //emit outputs from one observable
  13. const example = merge(
  14. first.pipe(mapTo('FIRST!')),
  15. second.pipe(mapTo('SECOND!')),
  16. third.pipe(mapTo('THIRD')),
  17. fourth.pipe(mapTo('FOURTH'))
  18. );
  19. //output: "FOURTH", "THIRD", "SECOND!", "FOURTH", "FIRST!", "THIRD", "FOURTH"
  20. const subscribe = example.subscribe(val => console.log(val));
Example 2: merge 2 observables, instance method

( StackBlitz |
jsBin |
jsFiddle )

  1. import { merge } from 'rxjs/operators';
  2. import { interval } from 'rxjs/observable/interval';
  3. //emit every 2.5 seconds
  4. const first = interval(2500);
  5. //emit every 1 second
  6. const second = interval(1000);
  7. //used as instance method
  8. const example = first.pipe(merge(second));
  9. //output: 0,1,0,2....
  10. const subscribe = example.subscribe(val => console.log(val));

Additional Resources


:file_folder: Source Code:
https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/merge.ts