concatMapTo

signature: concatMapTo(observable: Observable, resultSelector: function): Observable

Subscribe to provided observable when previous completes, emit values.

concatMapTo - 图1

Examples

Example 1: Map to basic observable (simulating request)

( StackBlitz )

  1. import { of } from 'rxjs/observable/of';
  2. import { interval } from 'rxjs/observable/interval';
  3. import { concatMapTo, delay, take } from 'rxjs/operators';
  4. //emit value every 2 seconds
  5. const sampleInterval = interval(500).pipe(take(5));
  6. const fakeRequest = of('Network request complete').pipe(delay(3000));
  7. //wait for first to complete before next is subscribed
  8. const example = sampleInterval.pipe(concatMapTo(fakeRequest));
  9. //result
  10. //output: Network request complete...3s...Network request complete'
  11. const subscribe = example.subscribe(val => console.log(val));
Example 2: Using projection with concatMap

( StackBlitz |
jsBin |
jsFiddle )

  1. import { interval } from 'rxjs/observable/interval';
  2. import { concatMapTo, take } from 'rxjs/operators';
  3. //emit value every 2 seconds
  4. const interval = interval(2000);
  5. //emit value every second for 5 seconds
  6. const source = interval(1000).pipe(take(5));
  7. /*
  8. ***Be Careful***: In situations like this where the source emits at a faster pace
  9. than the inner observable completes, memory issues can arise.
  10. (interval emits every 1 second, basicTimer completes every 5)
  11. */
  12. // basicTimer will complete after 5 seconds, emitting 0,1,2,3,4
  13. const example = interval.pipe(
  14. concatMapTo(
  15. source,
  16. (firstInterval, secondInterval) => `${firstInterval} ${secondInterval}`
  17. )
  18. );
  19. /*
  20. output: 0 0
  21. 0 1
  22. 0 2
  23. 0 3
  24. 0 4
  25. 1 0
  26. 1 1
  27. continued...
  28. */
  29. const subscribe = example.subscribe(val => console.log(val));

Additional Resources


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