Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between forkjoin and combineLatest rxjs

Both are used to join multiple streams.

From this I am confused between both, I read combineLatest make calls in sync mode and forkJoin calls parallel,

I am trying this

combineLatest([
      of(null).pipe(delay(5000)),
      of(null).pipe(delay(5000)),
      of(null).pipe(delay(5000))
    ]).subscribe(() => console.log(new Date().getTime() - start));

forkJoin([
      of(null).pipe(delay(5000)),
      of(null).pipe(delay(5000)),
      of(null).pipe(delay(5000))
    ]).subscribe(() => console.log(new Date().getTime() - start));

that prints

5004
5014

every time result is arround 5 sec, if combineLatest sends request in sequence then why it is printing duration arround 5 sec.

Is this correct or there is any other difference, any example code?

like image 894
Sunil Garg Avatar asked Aug 28 '26 05:08

Sunil Garg


1 Answers

Both subscribe to all source Observables in parallel and whether they are asynchronous depends only on each source Observable.

So in this use-case you'll get the same result. If you used concat() instead you would see difference because concat() subscribes to sources in sequence one after antother.

The difference between forkJoin and combineLatest is that forkJoin will emit only once when all source Observable emit at least one item and complete while combineLatest will emit every time any of the source Observables emit after they've emitted at least once.

like image 152
martin Avatar answered Aug 30 '26 16:08

martin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!