简体   繁体   中英

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

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
}) 

Instead of batching I recommend to use the concurrent value of some rxjs operators. mergeMap for example provides this value. After completing one observable, the next observable becomes subscribed to. Add finalize for 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM