Learn RxJS
  • Introduction
  • Learn RxJS
    • Operators
      • Combination
        • combineAll
        • combineLatest
        • concat
        • concatAll
        • endWith
        • forkJoin
        • merge
        • mergeAll
        • pairwise
        • race
        • startWith
        • withLatestFrom
        • zip
      • Conditional
        • defaultIfEmpty
        • every
        • iif
        • sequenceEqual
      • Creation
        • ajax
        • create
        • defer
        • empty
        • from
        • fromEvent
        • generate
        • interval
        • of
        • range
        • throw
        • timer
      • Error Handling
        • catch / catchError
        • retry
        • retryWhen
      • Multicasting
        • publish
        • multicast
        • share
        • shareReplay
      • Filtering
        • audit
        • auditTime
        • debounce
        • debounceTime
        • distinct
        • distinctUntilChanged
        • distinctUntilKeyChanged
        • filter
        • find
        • first
        • ignoreElements
        • last
        • sample
        • single
        • skip
        • skipUntil
        • skipWhile
        • take
        • takeLast
        • takeUntil
        • takeWhile
        • throttle
        • throttleTime
      • Transformation
        • buffer
        • bufferCount
        • bufferTime
        • bufferToggle
        • bufferWhen
        • concatMap
        • concatMapTo
        • exhaustMap
        • expand
        • groupBy
        • map
        • mapTo
        • mergeMap / flatMap
        • mergeScan
        • partition
        • pluck
        • reduce
        • scan
        • switchMap
        • switchMapTo
        • toArray
        • window
        • windowCount
        • windowTime
        • windowToggle
        • windowWhen
      • Utility
        • tap / do
        • delay
        • delayWhen
        • dematerialize
        • finalize / finally
        • let
        • repeat
        • timeInterval
        • timeout
        • timeoutWith
        • toPromise
      • Full Listing
    • Subjects
      • AsyncSubject
      • BehaviorSubject
      • ReplaySubject
      • Subject
    • Recipes
      • Alphabet Invasion Game
      • Battleship Game
      • Breakout Game
      • Car Racing Game
      • Catch The Dot Game
      • Click Ninja Game
      • Flappy Bird Game
      • Game Loop
      • Horizontal Scroll Indicator
      • Http Polling
      • Lockscreen
      • Matrix Digital Rain
      • Memory Game
      • Mine Sweeper Game
      • Platform Jumper Game
      • Progress Bar
      • Save Indicator
      • Smart Counter
      • Space Invaders Game
      • Stop Watch
      • Swipe To Refresh
      • Tank Battle Game
      • Tetris Game
      • Type Ahead
      • Uncover Image Game
    • Concepts
      • RxJS Primer
      • Get started transforming streams with map, pluck, and mapTo
      • Time based operators comparison
      • RxJS v5 -> v6 Upgrade
Powered by GitBook
On this page
  • Turn multiple observables into a single observable.
  • Why use merge?
  • Examples
  • Related Recipes
  • Additional Resources
  1. Learn RxJS
  2. Operators
  3. Combination

merge

PreviousforkJoinNextmergeAll

Last updated 1 year ago

signature: merge(input: Observable): Observable

Turn multiple observables into a single observable.


πŸ’‘ This operator can be used as either a static or instance method!

πŸ’‘ If order not throughput is a primary concern, try instead!


Why use merge?

The merge operator is your go-to solution when you have multiple observables that produce values independently and you want to combine their output into a single stream. Think of it as a highway merger, where multiple roads join together to form a single, unified road - the traffic (data) from each road (observable) flows seamlessly together.

A real-world example can be seen in a chat application, where you have separate observables for receiving messages from multiple users. By using merge, you can bring all those message streams into a single unified stream for displaying the messages in the chat window.

Keep in mind that merge will emit values as soon as any of the observables emit a value. This is different from combineLatest or withLatestFrom, which wait for each observable to emit at least one value before emitting a combined value.

Lastly, if you're dealing with observables that emit values at specific intervals and you need to combine them based on time, consider using the operator instead.

Examples

Example 1: merging multiple observables, static method

( | | )

// RxJS v6+
import { mapTo } from 'rxjs/operators';
import { interval, merge } from 'rxjs';

//emit every 2.5 seconds
const first = interval(2500);
//emit every 2 seconds
const second = interval(2000);
//emit every 1.5 seconds
const third = interval(1500);
//emit every 1 second
const fourth = interval(1000);

//emit outputs from one observable
const example = merge(
  first.pipe(mapTo('FIRST!')),
  second.pipe(mapTo('SECOND!')),
  third.pipe(mapTo('THIRD')),
  fourth.pipe(mapTo('FOURTH'))
);
//output: "FOURTH", "THIRD", "SECOND!", "FOURTH", "FIRST!", "THIRD", "FOURTH"
const subscribe = example.subscribe(val => console.log(val));

Example 2: merge 2 observables, instance method

// RxJS v6+
import { merge } from 'rxjs/operators';
import { interval } from 'rxjs';

//emit every 2.5 seconds
const first = interval(2500);
//emit every 1 second
const second = interval(1000);
//used as instance method
const example = first.pipe(merge(second));
//output: 0,1,0,2....
const subscribe = example.subscribe(val => console.log(val));

Related Recipes

Additional Resources


( | | )

πŸ“° - Official docs

- In Depth Dev Reference

πŸŽ₯ πŸ’΅ - John Linquist

πŸŽ₯ πŸ’΅ - AndrΓ© Staltz

πŸŽ₯ πŸ’΅ - AndrΓ© Staltz

πŸŽ₯ - Kwinten Pisman

πŸ“ Source Code:

StackBlitz
jsBin
jsFiddle
Battleship Game
Flappy Bird Game
HTTP Polling
Lockscreen
Memory Game
Save Indicator
merge
merge
Handling multiple streams with merge
Sharing network requests with merge
Combination operator: merge
Build your own merge operator
https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/merge.ts
concat
zip
StackBlitz
jsBin
jsFiddle