Skip to content
transformation

mergeMap

Projects each source value to an inner Observable and merges all inner Observables concurrently into a single stream.

Signature

mergeMap<T, R>(project: (value: T, index: number) => ObservableInput<R>): OperatorFunction<T, R>

Marble Diagram

source:    --a---------b---------|
mergeMap(x => interval(1).take(3))
result:    --a1-a2-a3--b1-b2-b3--|

Example

import { fromEvent } from 'rxjs'
import { mergeMap } from 'rxjs/operators'
import { ajax } from 'rxjs/ajax'

fromEvent(button, 'click').pipe(
  mergeMap(() => ajax.getJSON('/api/data'))
).subscribe(console.log)
// Each click triggers a new request; all run concurrently

Common Use Cases

  • Parallel HTTP requests triggered by a stream of events
  • Upload multiple files concurrently
  • { "Fan-out": "one event triggers many independent async tasks" }

Flow Diagram