Reactive Pattern for Bulk Operations

Explore the reactive pattern used to implement bulk operations.

Tasks as streams

We have to consider, as usual, our tasks as streams. The task that we’re going to perform is uploading the recipe image in the backend. So let’s imagine a stream called uploadRecipeImage$ that will take the file and the recipe identifier as input and perform an HTTP request. If we have n files to be uploaded, then we’ll create n streams.

We want to subscribe to all those streams together, but we’re not interested in the values emitted from each stream through the process; we only care about the final result (the last emission), whether the file is uploaded successfully, or whether something wrong happens and the upload fails.

Is there an RxJS operator that gathers a list of observables together to get a cumulative result? Yes, thankfully, we have forkJoin. Let’s look at the role and behavior of this operator.

The forkJoin operator

The forkJoin operator falls under the category of combination operators. If we look at the official documentation, we find this definition:

Accepts an array of ObservableInput or a dictionary Object of ObservableInput and returns an observable that emits either an array of values in the exact same order as the passed array or a dictionary of values in the same shape as the passed dictionary.

In other words, forkJoin takes a list of streams as input, waits for the streams to complete, and then combines the last values they emitted in one array and returns it. The order of the values in the array is the same as the order of the input observables.

Let’s consider the following marble diagram, as usual, to understand it better.

Get hands-on with 1200+ tech skills courses.