forkJoin: parallel http calls

v.7

v.18

Fabio Biondi
Google Developer Expert
Microsoft MVP
# forkJoin & ajax
forkJoin()
is an RxJS operator that waits for all provided observables to complete, and then emits the final combined result as an object.
The result is an object with two properties, values
and users
, which contain the last values emitted by their respective observable: 3
and an array of 10 users
The forkJoin
operators emits an object that contains the latest emitted value of each observable, in this scenario the number 3
and the array of users:
# forkJoin, ajax & delay
To show that forkJoin
waits for all observables to be completed, we now add a delay to the HTTP call so that it takes 2
seconds before issuing the value.
The result is the same but the difference is that now the result is emitted after 2 seconds, when all observables are completed::
The observable generated by the forkJoin
emits only one value after 2 seconds because the of
operator immediately emit the value while ajax.getJSON
emits its values after 2 seconds and after completes.
As we said, forkJoin()
waits for all provided observables to complete, and then emits the final combined result as an object.
# forkJoin & interval
See the next script.
In your opinion, what is the emitted value? Can you guess it?
This observable does not emit anything. Why?
Because the interval
never completes and we stated the forkJoin
emits the last value of each observable only when all of them complete.
Since the interval
never completes, forkJoin
never emits.
# forkJoin, interval and take operators
In order to allow forkJoin
to emit a value, the interval
should complete.
We can then use the take
operator.
An object with the latest value of each observable:
take operator
The take(n)
operator allows the observable to emit only the first n
values it produces, after which it automatically completes. If the source observable emits more than n
values, they will be ignored.
In the previous example, the interval
operator creates an observable that emits 5 sequential numbers (0, 1, 2, 3, 4) every 1000 milliseconds (1 second) since the take(5)
operator tells the observable to emit only the first 5 values.
After 5 emissions, the observable completes.
# Angular: parallel http requests
forkJoin
is used frequently in Angular when we need to perform multiple HTTP client operations and want to wait for the result of all operations to display the result or perform other operations.
For example, we might want to load a list of users
and a list of posts
from two different endpoints when a component is mounted.
At the end of the two fetches we can then display the data in the component template or perform other operations, with the certainty that both asynchronous operations have been performed successfully: