Crocsx
Crocsx

Reputation: 7609

Using rxjs to execute http call sequentially

I have those 4 api calls

1. HttpService.PostAsync<any, any>(`post_update_ac_translates`)
2. HttpService.PostAsync<any, any>(`post_start_auto_ac_mapping`)
3. HttpService.PostAsync<any, any>(`get_std_leaf_ac_items`)
4. HttpService.PostAsync<any, any>(`get_all_ac_translates`)

I want to execute them in this order

first execute 1, when completed 2, then after 2 is completed, 3 and 4 in the same time.

I tried to do this like this :

concat(
    HttpService.PostAsync<any, any>(`post_update_ac_translates`, {p_id: this.props.projectId, ac_trans: data}, HttpService.AuditcoreAPIBasePath),
    HttpService.PostAsync<any, any>(`post_start_auto_ac_mapping`, {p_id: this.props.projectId}, HttpService.AuditcoreAPIBasePath)
).subscribe(() => {
    forkJoin(
        HttpService.GetAsync<any, any>(`get_std_leaf_ac_items`, {p_id: this.props.projectId}, HttpService.AuditcoreAPIBasePath),
        HttpService.GetAsync<any, any>(`get_all_ac_translates`, {p_id: this.props.projectId}, HttpService.AuditcoreAPIBasePath)
    ).subscribe(([resp1, resp2]) => {

But the code is executing has follow

1 => 3/4 => 2 => 3/4

instead of

1=> 2 => 3/4

doing

HttpService.PostAsync<any, any>(`post_update_ac_translates`, {p_id: this.props.projectId, ac_trans: data}, HttpService.AuditcoreAPIBasePath).concat(

return an error

Property 'concat' does not exist on type 'AxiosObservable'.ts(2339)

Upvotes: 1

Views: 391

Answers (1)

wentjun
wentjun

Reputation: 42526

Instead of nesting the subscribe() calls, I would suggest the following method of chaining RxJS pipeable operators, as it might look cleaner.

HttpService.PostAsync<any, any>(`post_update_ac_translates`)
  .pipe(
    switchMap(() => HttpService.PostAsync<any, any>(`post_start_auto_ac_mapping`))
    switchMap(() => forkJoin(HttpService.PostAsync<any, any>(`get_std_leaf_ac_items`), HttpService.PostAsync<any, any>(`get_all_ac_translates`))
  ).subscribe([res1, res2] => {
     console.log(res1);
     // do the rest
  });

First, we use switchMap() to map the observable values from the first HTTP request into an inner observable, followed by making the second HTTP request. Then, we chain another switchMap() operator which will carry out the forkJoin operation which waits for the third and forth HTTP requests to be completed, before we subscribe and return the values from the observable.

Upvotes: 2

Related Questions