44

What's the way to simplify something like the following code example? I can't find the right operator.. could anyone give a short example?

this.returnsObservable1(...)
  .subscribe(

    success => {

      this.returnsObservable2(...)
        .subscribe(

          success => {

            this.returnsObservable3(...)
              .subscribe(

                success => {
                   ...
                },
1
  • 2
    You're probably looking for flatMap or switchMap operator. Mar 19, 2017 at 15:58

4 Answers 4

42

As mentioned in comments, you are looking for the flatMap operator.

You can find more details in previous answers :

Your example would read as :

this.returnsObservable1(...)
  .flatMap(success => this.returnsObservable2(...))
  .flatMap(success => this.returnsObservable3(...))
  .subscribe(success => {(...)}); 
2
  • 2
    @Robin Dijkhof So a function which is returning observable is used inside flatmap, .flatMap(success => this.returnsObservable2(...)) then this.returnsObservable2(...) don't i need to subscribe it ? Aug 18, 2019 at 18:52
  • 1
    flatMap is now called mergeMap Aug 19, 2022 at 14:10
32

Previously answered for RxJS 5, I ended up on this page whilst using 6.

In the case you're on 6 as well (and I think you should be by now) you can use flatmap as an operator within pipe.

Modified the example code of @user3743222:

this.returnsObservable1(...)
  .pipe(
    flatMap(success => this.returnsObservable2(...)),
    flatMap(success => this.returnsObservable3(...))
  )
  .subscribe(success => {(...)}); 
2
  • 2
    Could you give an example if returnsObservable2 would return an array of observables? Mar 31, 2020 at 19:47
  • 4
    Now flatMap is known as mergeMap (renamed). Jul 3, 2021 at 7:20
10

The switchMap operator can also be useful. Some examples which describe the usefulness of switchMap compared to nested subscriptions can be found here:

  1. situation with nested subscriptions

This codepen gives a demo: https://codepen.io/anon/pen/zdXBvP?editors=1111

Rx.Observable
  .interval(5000)
  .subscribe((val) => {
    console.log("outer:", val);
    Rx.Observable
      .interval(1000)
      .subscribe((ival) => {
        console.log("inner:", val, ival); 
      });
  });
  1. situation with switchMap

This codepen gives a demo: https://codepen.io/anon/pen/xLeOZW?editors=1111

Rx.Observable
  .interval(5000)
  .switchMap((val) => {
    console.log("outer:", val);
    return Rx.Observable.interval(1000).map((ival) => [val, ival]);
  })
  .subscribe((val) => {
    console.log("inner:", val[0], val[1]);
  });
3
  • Examples aren't necessarily enough, but thanks for sharing.
    – spakmad
    Sep 7, 2018 at 5:13
  • A general pattern I've found is to replace all "subscribes" with "switchMap" returning the next inner Observable. Then tack the most nested "subscribe" onto the end of the chain Dec 13, 2018 at 18:57
  • For nested subscriptions switchMap is the best approach.
    – epinal
    Nov 1, 2022 at 14:18
1

You basically need sequencing. With RxJS concat, you can just do this:

import { concat } from 'rxjs';
...

concat(
  this.returnsObservable1(...), 
  this.returnsObservable2(...), 
  this.returnsObservable3(...), 
  ...
)
.subscribe(success => {(...)});

If your subsequent observables need to know the values from the previous ones, you could use the RxJS concatMap operator.

import { concatMap } from 'rxjs/operators';
...

this.returnsObservable1(...)
  .pipe(
    concatMap(result1 => this.returnsObservable2(...)),
    concatMap(result2 => this.returnsObservable3(...)),
    ...
  )
  .subscribe(success => {(...)});

concat: https://www.learnrxjs.io/learn-rxjs/operators/combination/concat

concatMap: https://www.learnrxjs.io/learn-rxjs/operators/transformation/concatmap

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.