I'm learning about forkJoin
. I'm trying to wrap my head around how it works compared to creating an observable with of
. Please tell me if I have this right:
When I use of
, it creates an observable that will emit the value you pass to it right away. So if I have this:
const obs = of('hello');
obs.subscribe(console.log);
...it will log 'hello' as soon as the line where I subscribe to obs
executes. Is this correct?
Now if I have this:
const obs1 = httpClient.get(url1);
const obs2 = httpClient.get(url2);
const fjObs = forkJoin({obs1, obs2});
fjObs.subscribe(({obs1, obs2}) => console.log(`obs1=${obs1}, obs2=${obs2}`));
...it WON'T log obs1
and obs2
as soon as the line where I subscribe to fjObs executes. It will log them only when both obs1 and obs2 have completed, which could be a while after I subscribe to fjObs. Is this correct?
And until that happens, fjObs is just an observable that has not yet emitted any values. Is that correct?
Please let me know if my understanding is correct. Thank you.
Yes you are basically correct. Please note that as pointed out in the comment, this assumption was wrongforkJoin
accepts an array of observables, so your code should be: const fjObs = forkJoin([obs1, obs2]);
also you could test this:
forkJoin([of('one'), of('two')]).subscribe(console.log);
in this case the console.log will be executed immediatly since both of
emits immediatly.
you could also do: forkJoin([of('one'), httpClient.get(url1)]).subscribe(console.log);
in this case it will log after the HTTP request is completed.
You should not compare of
with forkJoin
since those are very different concepts.
of
creates an observable and forkJoin
combines an array of observables and emits (the last value of each observable) when all have emitted a value completed