mergeAll

signature: mergeAll(concurrent: number): Observable

Collect and subscribe to all observables.


:bulb: In many cases you can use mergeMap as a
single operator instead!


mergeAll - 图2

Examples

(
example tests
)

Example 1: mergeAll with promises

( StackBlitz |
jsBin |
jsFiddle )

  1. import { map, mergeAll } from 'rxjs/operators';
  2. import { of } from 'rxjs/observable/of';
  3. const myPromise = val =>
  4. new Promise(resolve => setTimeout(() => resolve(`Result: ${val}`), 2000));
  5. //emit 1,2,3
  6. const source = of(1, 2, 3);
  7. const example = source.pipe(
  8. //map each value to promise
  9. map(val => myPromise(val)),
  10. //emit result from source
  11. mergeAll()
  12. );
  13. /*
  14. output:
  15. "Result: 1"
  16. "Result: 2"
  17. "Result: 3"
  18. */
  19. const subscribe = example.subscribe(val => console.log(val));
Example 2: mergeAll with concurrent parameter

( StackBlitz |
jsFiddle )

  1. import { take, map, delay, mergeAll } from 'rxjs/operators';
  2. import { interval } from 'rxjs/observable/interval';
  3. const source = interval(500).pipe(take(5));
  4. /*
  5. interval is emitting a value every 0.5s. This value is then being mapped to interval that
  6. is delayed for 1.0s. The mergeAll operator takes an optional argument that determines how
  7. many inner observables to subscribe to at a time. The rest of the observables are stored
  8. in a backlog waiting to be subscribe.
  9. */
  10. const example = source
  11. .pipe(map(val => source.pipe(delay(1000), take(3))), mergeAll(2))
  12. .subscribe(val => console.log(val));
  13. /*
  14. The subscription is completed once the operator emits all values.
  15. */

Additional Resources


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