RxJS Functions (Part 6)
forkJoin
forkJoin
Joins last values emitted by passed Observables.
TL;DR
It’s like Promise.all. Pass in any number of ObservableInput. When every one completes, the Observable created by forkJoin
will emit an array of the last values for each input and complete.
Use Case
I could see countless uses for forkJoin
. But, since anything that takes Observable
also accepts Promise
, forkJoin
would be a good way to combine the two if necessary:
What’s going on here?
On line 8, an observable is setup to emit an incrementing number every second, starting from zero. It’s piped through take(3)
which tells the observable to complete after 3 emissions.
Line 11 sets up a new promise which resolves after 1 second with the value ‘Chainz’.
On line 14, forkJoin
is called with the Observable
, the Promise
, and a project function. When the Observable
completes, and the Promise
resolves, the project function combines the last value from the Observable
with the value from the resolved Promise
into a string: ‘2 Chainz’. That string is emitted, and the Observable
created by forkJoin
completes.
Thanks for reading. Stay tuned for Part 7, and be sure go checkout my previous articles.