0

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?

Sunil Garg
  • 14,608
  • 25
  • 132
  • 189

1 Answers1

3

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.

martin
  • 93,354
  • 25
  • 191
  • 226
  • by mistake i was using combineLatest with two http calls, but in that case i was getting result only once, so if combinelatest emits everytime when one of source emit then i should get two calls? – Sunil Garg Nov 17 '20 at 11:23
  • `combineLatest` will emit every time any of the source Observables emit **after they've emitted at least once.** – martin Nov 17 '20 at 11:24
  • concat i guess deprecated now? – Sunil Garg Nov 17 '20 at 11:24
  • 1
    `concat` isn't deprecated. Depending on what version of RxJS you use it might be imported as `import { concatWith } from 'rxjs';` or with v6 `import { concat } from 'rxjs';` – martin Nov 17 '20 at 11:25
  • so forkJoin will not get call if sources emit the second value? – Sunil Garg Nov 17 '20 at 11:26
  • 1
    `forkJoin` will emit only once after all sources complete with the latest value from each source Observable. – martin Nov 17 '20 at 11:27