Renuka Dasari
Renuka Dasari

Reputation: 61

Angular 2 - Synchronous http calls using flatmap is not performing the next calls when an empty observable is returned

I am performing three synchronous calls in this manner

this.deletePreallocations()
     .flatMap(() => {
         return this.postPreallocations();
     })
     .flatMap(() => {
         return this.postPayment();
     })
     .takeWhile(() => this.isAlive)
     .subscribe(
         () => { },
         err => {
            console.log(err);
      });

And each calls are like this

deletePreallocations() {
      if (this.preAllocationsDeleteIds.length > 0) {
         let self = this;
         let prealloctionsDeleteIDs = this.preAllocationsDeleteIds.filter(function (item, index) { return self.preAllocationsDeleteIds.indexOf(item) === index; });
         return this.paymentsService.deletePreallocations(this.payment.ID, prealloctionsDeleteIDs);
      }
      return Observable.empty();
   }

   postPreallocations() {
      if (this.preallocationupdatedValues.length > 0) {
         return this.paymentsService.postPreallocationsCollection(this.payment.ID, this.preallocationupdatedValues);
      }
      return Observable.empty();
   }

   postPayment() {
      return this.paymentsService.post(this.payment);
   }

So the problem is when the returned observable is empty, it is not performing the next calls. Can someone suggest what is wrong with this code.

Thanks

Upvotes: 1

Views: 379

Answers (1)

martin
martin

Reputation: 96889

That's correct because flatMap works only with the next notifications and Observable.empty() sends only the complete notification and nothing else.

So what you can do is not to rely on the next notification and just wait until the previous Observable completes:

this.deletePreallocations()
     .concat(Observable.defer(() => this.postPreallocations()))
     .concat(Observable.defer(() => this.postPayment()))
     .takeWhile(() => this.isAlive)
     .subscribe(
         () => { },
         err => {
            console.log(err);
         }
     );

I'm using Observable.defer that calls its callback only when you subscribe to it. Since in this.postPreallocations() and this.postPayment() you have some logic that depends on an internal state this should guarantee that these methods will be called only when concat tries to subscribe.

Upvotes: 1

Related Questions