Is it possible for RXJS forkJoin to accept an Observable with an array as the type parameter?

Transforming an array of numbers into observables that emit at random times is a task I have been working on.

Once all the observables are resolved, I display the final result.

To achieve this, I am utilizing forkJoin, similar to how one would use promise.all.

let arr: Array<Number> = [1, 2, 3, 4, 5];
let d = from(arr).pipe(mergeMap(f => myPromise(f)), toArray());
const example = forkJoin(d);
const subscribe = example.subscribe(val => console.log(val));

The results are indeed showing up after a randomized maximum time period, as expected.

Upon revisiting the documentation, it seems that what I have implemented should not actually be working as intended.

https://i.sstatic.net/u5QHI.png

It is important to note that the variable d holds the type Observable <{}[]>, making it an observable of an array.

However, according to the documentation:

sources :SubscribableOrPromise Any number of Observables provided either as an array or as arguments passed directly to the operator.

In my case, I am not passing an array directly. As a result, using forkJoin(...d) will not yield the desired outcome.

Question:

Is my usage of forkJoin incorrect? How does this conflict with the documented behavior?

Online Demo

Answer №1

It appears that the usage of mergeMap and toArray seems to be working, but upon closer inspection of the output, it may not be producing the intended results. The output shows the resulting array nested within another array, whereas it seems like you were aiming for a single array of results.

Here is the current output:

https://i.sstatic.net/9lFe7.png

[
  [ "Promise Resolved: 1", "Promise Resolved: 2", "Promise Resolved: 3", "Promise Resolved: 4", "Promise Resolved: 5" ],
]

The reason behind this behavior is that mergeMap is being used to convert each number into a Promise, followed by toArray to gather all the results before completing the chain (resulting in a single emission of the array). Therefore, when using forkJoin, it subscribes to the overall Observable after toArray, which explains the observed outcome.

The documentation is accurate as it caters to various use cases, such as:

forkJoin(a, b, c); // Observables passed directly as arguments to the operator

or

forkJoin([a, b, c]); // Observables provided as an array

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Experiencing difficulty moving information from React form to DATA.txt file through Express

I've tried various things, but I keep encountering the same error. Changing the file path didn't seem to make a difference. The current structure of my project is as follows: {nodemodules,public,scr (containing all files including App.jsx),DATA. ...

The Model.updateOne() function seems to be failing to update some fields

I am attempting to execute a PATCH update on a MongoDB document. I fetch the existing document using Mongoose in the following manner: const ratePlan = await RatePlan.findOne({ _id: req.params.id, }) The code snippets provided above work effectively in ...

For the past two days, there has been an ongoing issue that I just can't seem to figure out when running npm start

After multiple failed attempts, I have exhausted all troubleshooting steps including executing npm clear cache --force, deleting node_modules/ and package-lock.json, followed by running npm install, npm build, and eventually npm run dev. The errors encoun ...

What could be causing my web application to not properly identify angular.js?

As a newcomer to angular, I have been struggling to incorporate it into my web application (VS) as I keep encountering issues with recognizing angular. Despite trying various methods, the result remains the same - angular is not being recognized. I dow ...

Fragment shader error occurs when multiple lights casting shadows are used in three.js

Imagine a scenario where you have a street with numerous streetlights (over 20) and you position an object nearby, expecting to see a shadow. The lights are represented as: var light = new THREE.PointLight(0xffffff, 0.5, 6.0); Only the street has .recei ...

The ValidationMessageFor tag is failing to function on the view page

I am currently in the process of updating the styling from bootstrap 3 to bootstrap 5. The issue I am facing is that in the bootstrap 3 version, when I click the "save" button without filling any text boxes, the page displays a validation message like this ...

Calculating the height of a window using JavaScript and Ajax

As you navigate down the page, new images start loading at the bottom. However, I want them to load before reaching the very end of the page. Below is the code snippet from the page template: <?php /** * Template Name: gallery */ get_header(); ?> ...

Implement an onclick event for a dynamically generated link in PHP

I have a collection of links generated dynamically using PHP and I am now looking to include an onclick event. while($row = mysqli_fetch_array($xyz)) { echo "<tr>"; echo "<td><a href=\"test.php?parameter=". $row ...

Is there a way to show both miles-per-hour and kilometers per hour side by side

Is it possible to display both miles per hour and kilometers per hour together? How can I incorporate the calculation for kilometers per hour and showcase it alongside miles per hour? function getMiles (knots) { var mph = (knots * 1.15078); va ...

Matching email addresses using regex in Javascript

I am encountering an issue with the else if block in my Javascript code. It seems to be blocking all email IDs, even correct ones. Can someone assist with understanding what the match() function returns? I have tested the following scenarios: - Empty fie ...

Are Angular2 Injectables for creating instances or referencing the same instance?

Exploring the world of ES6, TypeScript, and Angular2 has been quite a journey for me. I recently delved into directives and here's what I found... import { Directive, ElementRef, Input, Renderer } from '@angular/core'; @Directive({ selecto ...

Vue.js is not incrementing the counter as expected

I've encountered an issue with a button that has a click event to increment data value by 5, but instead of adding 5 it is appended by 5. Click here for the code example <div id="react"> <button @click='counter += 5'>Increment& ...

Deprecated message received from the body-parser node module

Currently learning Node.js, I've been utilizing the 'express' framework and installed body-parser successfully. However, upon starting my app, I encountered this message from Node: body-parser deprecated bodyParser: use individual json/urle ...

Adding JSON data to an array with a click - a step-by-step guide

As I dive into working with React and integrating API JSON data into my project, I've encountered a small hurdle. I've implemented a function that allows users to enter a search query, resulting in a list of devices associated with their input be ...

What could be causing the component not to display the accurate data in ReactJS?

Currently, I am working on rendering an array of values along with two buttons - one for adding and the other for removing elements. Everything seems to be working fine, except for the removal functionality. When I click on the Remove button for a specific ...

Storing JSONP data in a variable: Tips and Tricks

Having an issue with storing JSONP data into variables and using it as input for a Google Pie Chart. Consider the following: Data in test.json: { "name": "ProjA", sp": 10, "current": 20 } The goal is to retrieve the SP value. Attempted solution usin ...

JavaScript and HTML have encountered an Uncaught TypeError: The property 'addEventListener' cannot be read because it is null

Having an issue here. Whenever I try to play sound from an image, I encounter an error. Uncaught TypeError: Cannot read property 'addEventListener' of null Here is my HTML code: <html> <head> <title>Music</title> < ...

What is the best way to exclude the `default` entry while looping through a local JSON file?

For my project, I'm incorporating a JSON file from my local directory in the following manner: import * as RULES from './json/rules.json'; After importing it, I attempt to loop through its entries using the code snippet below: const rules ...

Innovative dynamic form tool that seamlessly integrates with JSON schema for React

I have a question about finding a library that can generate and validate forms based on JSON schema. Before I start coding, I want to explore if there are existing solutions available. I've come across the ajv library for validation, but I'm uns ...

Thumbnail Carousel Caption in Bootstrap 3

Is it possible to create a Bootstrap 3 carousel where the image changes when the mouse cursor hovers over the thumbnail under the carousel? Currently, I have a setup with the carousel and thumbnails below it. Typically in Bootstrap, the image changes autom ...