merge

签名: merge(input: Observable): Observable

将多个 observables 转换成单个 observable 。


:bulb: 此操作符可以既有静态方法,又有实例方法!

:bulb: 如果产生值的顺序是首要考虑的,那么试试用 concat 来代替!


merge - 图3

示例

示例 1: 使用静态方法合并多个 observables

( StackBlitz |
jsBin |
jsFiddle )

  1. import { mapTo } from 'rxjs/operators';
  2. import { interval } from 'rxjs/observable/interval';
  3. import { merge } from 'rxjs/observable/merge';
  4. // 每2.5秒发出值
  5. const first = interval(2500);
  6. // 每2秒发出值
  7. const second = interval(2000);
  8. // 每1.5秒发出值
  9. const third = interval(1500);
  10. // 每1秒发出值
  11. const fourth = interval(1000);
  12. // 从一个 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. // 输出: "FOURTH", "THIRD", "SECOND!", "FOURTH", "FIRST!", "THIRD", "FOURTH"
  20. const subscribe = example.subscribe(val => console.log(val));
示例 2: 使用实例方法合并2个 observables

( StackBlitz |
jsBin |
jsFiddle )

  1. import { merge } from 'rxjs/operators';
  2. import { interval } from 'rxjs/observable/interval';
  3. // 每2.5秒发出值
  4. const first = interval(2500);
  5. // 每1秒发出值
  6. const second = interval(1000);
  7. // 作为实例方法使用
  8. const example = first.pipe(merge(second));
  9. // 输出: 0,1,0,2....
  10. const subscribe = example.subscribe(val => console.log(val));

其他资源


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