Shofol
Shofol

Reputation: 733

How to manage multiple sequential subscribe methods in Angular and RxJs?

I need to call two http service calls and subscribe them after subscribing another one http service call. I mean, the operation will be sequential as the last two calls depend on the first one. Can this operation be handled with concatMap of RxJs?

I solved the problem using nested subscription. But, I think using concatMap, this can be done. In all examples I searched, there are two calls which are concatenated. How to concat more than two subscription and solve the issue.

this.accountService.fetchBranchCodeLength().subscribe(
        data => {
            this.branchCodeLength = +data;


    //Now, I need to call another service to calculate 
    accountNumberLengthWithProductCode//


   this.subscribers.fetchAcoountNumberLength = 
    this.accountService.fetchAccountLengthConfiguration().subscribe(
      accountLength => {
        this.accountNumberLengthWithProductCode = 
            (+accountLength) - (+this.branchCodeLength);});


    //Another same kind of call to calculate 
    SUBGLCodeLength//


   this.subscribers.fetchSUBGLCodeLengthSub = 
     this.glAccountService.fetchSUBGlCodeLength(SUBGlCodeQueryParam)
      .subscribe(length => this.SUBGLCodeLength = 
          (+length.value) - (+this.branchCodeLength)                        
    );
  }
);

Upvotes: 0

Views: 7096

Answers (1)

Amir Arbabian
Amir Arbabian

Reputation: 3699

Concat map is used when you have a lot of requests, but when they are similar, it means they will have the same output data and handler, which is not your case. So you can use forkJoin, because there are no any dependencies among your calls.

Code

forkJoin(
   this.accountService.fetchBranchCodeLength(),
   this.accountService.fetchAccountLengthConfiguration(),
   this.glAccountService.fetchSUBGlCodeLength(SUBGlCodeQueryParam)
).subscribe(([data, accountLength, length]) => {
   this.branchCodeLength = +data;
   this.accountNumberLengthWithProductCode = (+accountLength) - this.branchCodeLength
   this.SUBGLCodeLength = (+length.value) - this.branchCodeLength;
});

And by the way, you do not need to unsubscribe from http call observables, because they are finite (to be precise the emit only one event).

Upvotes: 7

Related Questions