Want to call multiple api calls in batch format using forkJoin in angular/Ionic

793 views Asked by At

I have array of requests like:

let array = [req1,req2,req3.....,req(n)]

Currently I am using forkJoin to call a subscriber only after getting all requests response. Now I want to modify my code to make api calls in batch but call subscriber only after complete all batches response get is it possible?

example

public demoCalls() {
       let demoForkJoin
       var a = [req1,req2,....,req45]
       a.map((data,index)=>{
            demoFrokJoin[index] = this.http.post()
       })
       forkJoin(demoForkJoin)

}

Now instead of this, I want to call 10-10 req in batch. Each 10 req will be call after 1000ms

And one subscriber will be called only after getting response from all API's. (all 45 api's)

demoCall().subscribe(res=>{
  // this subscribe only once after all calls are completed and got success result
}) 
1

There are 1 answers

0
MoxxiManagarm On

Instead of batching I recommend to use the concurrent value of some rxjs operators. mergeMapfor example provides this value. After completing one observable, the next observable becomes subscribed to. Add finalizefor the finish action.

Following example has 2 concurrent requests

import { Observable, of, range } from 'rxjs';
import { delay, finalize, mergeMap } from 'rxjs/operators';

function req(id: number): Observable<number> {
  console.log('request received for id', id);

  return of(id).pipe(delay(5000));
}

range(0, 10)
  .pipe(
    mergeMap((r) => req(r), 2),
    finalize(() => console.log('all requests done'))
  )
  .subscribe((id) => console.log('request completed for id', id));

See this in action on Stackblitz: https://stackblitz.com/edit/typescript-cmylca?file=index.ts