1

Angular 6 : Angular Multiple HTTP Requests with RxJS (updatePhone and updateAddress) that NOT rely on each other but both may or may not execute together.

case 1: Changes made to Address fields (address, state, city or zip), I require to call updateAddress api.

case 2: Changes made to Phone fields (phoneNumber or phoneType), i require to call updatePhone api.

case 3: If both address and phone got change, i require to change updateAddress & updatePhone api.

I tried

import { forkJoin, combineLatest, Observable } from 'rxjs';

let phoneUpdate, addressUpdate;

if (this.isPhoneUpdateApi)
  phoneUpdate = this.customerService.updatePhone(phoneUpdateRequest);
if (this.isAddressUpdateApi)
  addressUpdate = this.customerService.updateAddress(addressUpdateRequest);

  const combined = combineLatest(phoneUpdate, addressUpdate);
  combined.subscribe(
    ([phoneUpdateResponse, addressUpdateResponse]) => {
      console.log(
        `Phone Update Response: ${phoneUpdateResponse.model},
         Address Update Response: ${addressUpdateResponse.model}`
      );
      this.isPhoneUpdateApi = false;
      this.isAddressUpdateApi = false;
      console.log('this.isAddressUpdateApi', this.isAddressUpdateApi, 'this.isPhoneUpdateApi', this.isPhoneUpdateApi);
    });

But here combineLatest() is not working if only Phone changes and NOT Address change.

I am not sure how to handle this situation.

5
  • You can use forkJoin instead, which will allow them to execute at the same time Commented Aug 23, 2018 at 15:38
  • forkJoin When all observables complete, emit the last emitted value from each. but i have situation i might not call one api. situation where phone got change but address did not. Commented Aug 23, 2018 at 15:43
  • That's it. Would that work for you? Commented Aug 23, 2018 at 15:44
  • forkJoin(phoneUpdate, addressUpdate, (phoneUpdateResponse, addressUpdateResponse) => { return { phoneUpdateResponse, addressUpdateResponse }; }); Commented Aug 23, 2018 at 15:45
  • i tried above code but its NOT working. Commented Aug 23, 2018 at 15:47

1 Answer 1

1

You can use forkJoin for this.

reqs = [];
if (shouldUpdatePhone) {
   reqs.push(this.customerService.updatePhone(phoneUpdateRequest))
}
if (shouldUpdateAddress) {
   reqs.push(this.customerService.updateAddress(addressUpdateRequest))
}

forkJoin(reqs).subscribe(result => {
   // Do whatever you want when they're both done.
});
Sign up to request clarification or add additional context in comments.

1 Comment

I have question on error handling with this approach. i have added new question stackoverflow.com/questions/51993575/…

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.