Does forkjoin return results in a particular order?

Viewed 2647

My app will make multiple parallel http call. Its based on a switch-fall though logic, so the number of query will vary (1, 2, or 3 calls). Is there a way for me to know which call gets returned first? I.e either assign a key or does it return in an ordered way based on the http request on the list?

Either way works for me. I just need to find a way to match the right result with the right call.

3 Answers

Yes it returns the results in the same order that you make requests in an array

example,

const bothrequests= Observable.combineLatest(
  this.http.get('https://testdb1.com/.json').map((res: Response) => res.json()),
  this.http.get('https://testdb2.com/.json').map((res: Response) => res.json())
)
bothrequests.subscribe(latestValues => {

});

It is ordered based on the order of the requests.

Try

const { merge, of } = rxjs;
const { bufferCount, take, delay } = rxjs.operators;

let r1 = of("A").pipe(delay(1000));
let r2 = of("C").pipe(delay(3000));
let r3 = of("D").pipe(delay(4000));
let r4 = of("B").pipe(delay(2000));

// in forkJoin(r1,r2,r3,r4) we get:      [A,C,D,B]
// in this we get sorted by finish time: [A,B,C,D]

merge(r1,r2,r3,r4)
  .pipe(bufferCount(4), take(1))      
  .subscribe(console.log)
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.5/rxjs.umd.min.js" integrity="sha256-85uCh8dPb35sH3WK435rtYUKALbcvEQFC65eg+raeuc=" crossorigin="anonymous"></script>

Related