How Can We Avoid forkJoin Problems?

In the forkJoin subscribe method, you should be less interested in the data coming from observables and focus on the fact that all observables have completed.

Acquiring the data may not be the concern of the forkJoin subscribe . It could be more about making sure the data is already fully available and can be safely used.

Data storing can very often be moved directly to the observables passed to forkJoin as arguments. We could use the RxJS tap operator to handle data processing there, like so:

See how everything became simplified by applying this one simple trick. We now have a very simple subscribe method and most of the data processing handled directly in the observables passed to the forkJoin .

We separated concerns; the date range is stored in private fields directly by the dateRange$ observable, the setUsers method is run by the users$ observable, and finally, the chart’s configuration is acquired and set right after calling the API.

But we still have some array indexes appearing in the subscribe method and we already know it’s bad. We cannot move the code to the observables directly as the method depends on data coming from two of those observables and both need to finish before it can be run.

How can we help ourselves? Well, we could introduce another private field to store the data and deal with the problem, like in case of other observables in the example. We could also create a nested forkJoin just to handle those two observables separately. But instead, let’s use the simplest solution: destructuring arrays.

As you can see we now have fully readable forkJoin code without any of the downsides described above. We have named the elements of the array that we are interested in and used those names in the code. It looks way better now:

We no longer have any data accessed by the array indexes in the subscribe method.

But maybe you already noticed that we still need to count commas in the destruturing notation! Can we fix it easily? Actually yes, as we now only use data coming from two observables in the subscribe method. Let’s reorder observables in the forkJoin :