Search code examples
rxjsobservablefork-joincombinelatest

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?


Solution

  • 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.