Concat and Merge Operator

Concat and Merge Operator

In this tutorial, we will learn about from Concat and Merge operator of RXJS.

Concat Operator:

Concat Subscribe to observables in order as previous completes

You can think of concat like a line at an ATM, the next transaction (subscription) cannot start until the previous complete!

Example:

 const source = interval(1000).pipe(
      map((v) => "Tech Video #" + (v + 1)),
      take(5)
    );
    const source2 = interval(1000).pipe(
      map((v) => "Comedy Video #" + (v + 1)),
      take(3)
    );
    const source3 = interval(1000).pipe(
      map((v) => "News Video #" + (v + 1)),
      take(4)
    );

    const finalObs = concat(source, source2, source3);

    finalObs.subscribe((res) => {
      console.log(res);
    });

It will Output:

Tech Video #1
Tech Video #2
Tech Video #3
Tech Video #4
Tech Video #5
Comedy Video #1
Comedy Video #2
Comedy Video #3
News Video #1
News Video #2
News Video #3
News Video #4

Merge Operator:

Merge Turn multiple observables into a single observable

If throughput, not order, is a primary concern, try merge instead!

    const source = interval(3000).pipe(
      map((v) => "Tech Video #" + (v + 1)),
      take(5)
    );
    const source2 = interval(4000).pipe(
      map((v) => "Comedy Video #" + (v + 1)),
      take(3)
    );
    const source3 = interval(3500).pipe(
      map((v) => "News Video #" + (v + 1)),
      take(4)
    );

    const finalObs = merge(source, source2, source3);

    finalObs.subscribe((res) => {
      console.log(res);
      this._desingUtility.print(res, "elemet1");
    });

Output:

Tech Video #1
News Video #1
Comedy Video #1
Tech Video #2
News Video #2
Comedy Video #2
Tech Video #3
News Video #3
Tech Video #4
Comedy Video #3
News Video #4
Tech Video #5

Subscribe to our Newsletter

Stay up to date! Get all the latest posts delivered straight to your inbox.

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

You might also like

Leave a Comment