0
votes

I would like to know which is the right approach for executing diferent http request when a reactive form control changes its value avoiding nested subscriptions.

I have two ways but i am not sure this are the most efficient ways.

OPTION 1:

this.form.get('someControl').valueChanges.pipe(debounceTime(500))
.subscribe(value => {

  /* Http Request 1 */
  http1$= this.http.post(route1, value).subscribe( res=>
  /*Tasks for Http Request1 */ 
 );

  /* Http Request 2 */
  http2$= this.http.post(route2, value).subscribe( res=>
  /*Tasks for Http Request2 */ 
 );
});

This option doesn´t use switchMap so every time the outer observable fires a new subscription is created but the old is not cancelled. :(

OPTION2:

/* Http Request 1 */
this.form.get('someControl').valueChanges.pipe(debounceTime(500),
 switchMap(value=> this.http.post(route1, value)))
.subscribe(res=> {
  /*Tasks for Http Request1 */ 
 );
)};

/* Http Request 2 */
this.form.get('someControl').valueChanges.pipe(debounceTime(500),
 switchMap(value=> this.http.post(route2, value)))
.subscribe(res=> {
  /*Tasks for Http Request2 */ 
 );
)};

Is there a way to make the calls subscribing only once to the valueChanges event?

Thank you in advance.

1

1 Answers

1
votes

You could use RxJS forkJoin operator to combine multiple requests. Try the following

this.form.get('someControl').valueChanges.pipe(
  debounceTime(500),
  switchMap(value => forkJoin(this.http.post(route1, value), this.http.post(route2, value)))
).subscribe(
  response => {
    // response[0] - response from 'this.http.post(route1, value)'
    // response[1] - response from 'this.http.post(route2, value)' 
  },
  error => {
    // handle error
  }
);