I'm new to RXJS and I have a working piece of code for http-request and subscribing to Observables from a shared service in Angular. This works, but I'd want to get rid of the nested subscriptions, which I know is probably very possible with RXJS operators, but I haven't figured out how. The usage of flatMap in the nested request wouldn't be necessary, as the second nested request isn't dependable on the first.

  this.sub = this.service.isPending$
    .subscribe(data => {
      if(data) { // gives boolean
          .subscribe((data:Offer) => this.offer = data)
      } else {
        this.sub2 = this.service.amount$
        .flatMap((data: Amount) => {
          this.amount = data;
          return this.service.getOffer()
        .subscribe((data: Offer) => {
          this.offer = data;

How would I go about cleaning this code up? I'm using RXJS: "^5.0.1"


1 Answer 1


On Observables

My personal preference is to have as few Subscription objects and subscribe() invocations as possible. If I don't have mistakes in the refactored code, you can achieve a single subscribe() which does the same things as your code. I also got rid of sub2.

this.offerSubscription = this.service
    .flatMap(data => {
        this.amount = null;
        const offerObservable = data ?
            this.service.getPending() :
                .flatMap((data: Amount) => {
                    this.amount = data;
                    return this.service.getOffer();
        return offerObservable;
    .subscribe((offer: Offer) => this.offer = offer);

On TypeScript

sub, sub2, isPending$ and data are pretty bad names because they don't describe the entities they hold. I recommend changing them.

At the bare minimum, specify the type of the input parameter in your arrow function to make the code more readable: (data: Offer) => {...} or better (receivedOffer: Offer) => { ... }.

  • \$\begingroup\$ Specifying the type of a callback parameter is very much like an implicit type assertion and masks the introduction of any. \$\endgroup\$ Commented Mar 12, 2018 at 9:45

Your Answer

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

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