A comparison between RXJS5 and Promise.all

Is there a Promise.all equivalent in this situation?

let promise1 = performTaskA(); // some promise
let promise2 = performTaskB(); // another promise

// wait for both promises to complete.
Promise.all([promise1, promise2], data => {
    // do something;
}); 

I can't seem to figure it out from the documentation. Some articles mention ForkJoin, but I'm having trouble making it work...

let source1 = new BehaviorSubject(0);
let source2 = new BehaviorSubject(1);
let combinedObservable = new ForkJoinObservable(source1, source2);

source1.subscribe( () => console.log('I am working'));
source2.subscribe( () => console.log('I am working'));
combinedObservable.subscribe( () => console.log('I am not working'));

Maybe I should just go back to using plain old promises.

Answer №1

Rx.Observable provides a handy toArray function that mimics the behavior of Promise.all: it gathers all values emitted by the stream and waits for the stream to complete before emitting a single item containing all the values:

// Instead of relying on Promises, we can use observables for asynchronous actions
const task1$ = Rx.Observable.of(1);
const task2$ = Rx.Observable.of(2);

// Merge all tasks into one stream
const combined$ = Rx.Observable.merge(task1$, task2$)

// Use toArray to collect all results
combined$
    .toArray()
    .subscribe(result => console.log(result));
// >> [1, 2]

Answer №2

import Rx, { Observable } from 'rxjs' 
import axios from 'axios'

const userPromise1 = axios.get('https://jsonplaceholder.typicode.com/users/1')
    , userPromise2 = axios.get('https://jsonplaceholder.typicode.com/users/2')

const userStream$ = Observable   
       .of(userPromise1, userPromise2)       
       .flatMap(promise=>promise)    
       .map(response=>response.data)   
       .map(user=>user.name)   
       .subscribe(
           name=>console.log(`Displaying name: ${name}`)
           // Displaying name: Ervin Howell
           // Displaying name: Leanne Graham   
       )

flatMap(promise=>promise) is a technique to automatically resolve promises

Answer №3

An alternative approach is to utilize the toPromise method:

Promise.all([behaviour1.toPromise(), behaviour2.toPromise()])

The toPromise function generates a promise that resolves upon completion of the observable.

For cases where observables emit multiple values before completion, operations like zip, combineLatest and withLatestFrom may be more suitable:

zip

Each value from behavior1 aligns with a corresponding value from behavior2. If either source depletes its values, processing pauses until new values are available.

Observable.zip(behavior1, behavior2)
  .subscribe(([b1, b2]) => console.log(b1, b2))

References: Documentation, Interactive illustration

combineLatest

Similar to zip, but emits a value whenever behavior1 or behavior2 produces an output, utilizing the latest value from the other observable.

Observable.combineLatest(behavior1, behavior2)
  .subscribe(([b1, b2]) => console.log(b1, b2))

References: Documentation, Interactive illustration

withLatestFrom

Comparable to combineLatest, but only one observable dictates emission timings.

behavior1.withLatestFrom(behavior2)
  .subscribe(([b1, b2]) => console.log(b1, b2))

References: Documentation, Interactive illustration

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

Issue encountered while configuring 'innerHTML' in xmlHttp.onreadystatechange function

Trying to create a JavaScript function that changes the innerHTML of a paragraph within an xmlHttp.onreadystatechange function, I encountered an error in the Chrome Console: Uncaught TypeError: Cannot set property 'innerHTML' of null at XMLH ...

React Component State in JavaScript is a crucial aspect of building

What happens when the expression [...Array(totalStars)] is used within a React Component? Is the result an array with a length of 5, and what are the specific elements in this array? We appreciate your response. class StarRating extends Component { ...

Implementing authentication with JSONP requests in Angular

When using JSONP on a request with basic auth, it is necessary to include the Authorization header in the request to retrieve the token. Upon testing this: $scope.doRequest = function() { $http({method: 'JSONP', url: 'http://apilder-ap ...

Instructions on configuring the oddslib JavaScript library

I am experimenting with a unique odds library I discovered at the following link: https://github.com/1player/oddslib Interestingly, upon importing it, I encountered a warning. I followed the setup for oddslib by running npm install oddslib Despite that ...

Trouble with executing a jQuery dynamic loop for each item

I have a unique situation where I am dealing with a table containing multiple tables for various users. The number of users can vary, so I am aiming to create a dynamic solution. Below are two sample tables for reference. <div class="timecard"> < ...

Execute the file separately using dot.js

When working on my project, I decided to include a header.def file in index.dot by using the {{#def.header}} snippet. To render the index.dot file, I utilized the following snippet: var dotjs = require('dot'); var dots = dotjs.process({ path: ". ...

Using AJAX to transform octet-stream into typed array (Float64Array)

I can't seem to figure out where I'm going wrong here. My attempt involves converting a binary stream obtained from an AJAX request into an array of doubles using JavaScript. Here is some of my code: The PHP script on my server returns an octet-s ...

Building a dynamic web form using JSP and Angular for the JEE platform

I am currently working on a banking project using JSP and angular 1.3.2. I have encountered an issue with a form where, upon blurring after typing the customer number, the customer's information such as name and address should be displayed if the cust ...

Transmit data to Angular components using the router functionality

Within Angular 2, I have established my routing system in app.module.ts: const appRoutes: Routes = [ { path: '', component: HomeComponent, }, { path: 'admin', component: AdminComponent, } ]; Furthermore, there ...

Div sliding out of view

I'm encountering a slight issue with this template: essentially, my goal is to implement a feature where clicking on a box will expand it while simultaneously sliding the other boxes off-screen. However, instead of just sliding the div off-screen, it ...

Want to make your JS loop lightning fast?

Today I stumbled upon an interesting idea to test the performance of a loop that I have cleverly named "scoped for". The concept is quite simple. This loop consists of two variables, "i" and "l", which are defined at one scope higher than the loop itself. ...

Error message: Incorrect XMP data detected within PhotoSphereViewer" and "WebGL issue: INVALID_VALUE error when attempting to load faulty image data

I'm currently utilizing Photo Sphere Viewer to showcase a panoramic image similar to how Facebook does it, but I am encountering some difficulties. Below is the code snippet: <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/em ...

Passing parameters as an array in Angular can be done by using the format: ?category[]=1&category[]=2&category[]=3,

Struggling to send an array using the $http.get() method in AngularJS. Here's my current approach: $http.get('/events.json', {params: {category_id: [1,2]}}); While I anticipate the request to be sent as /events.json?category_id[]=1&cat ...

How can you implement div slide animations using AngularJS?

Is there a way to slide a div when a user clicks on a tab? I have created a demo in jQuery Mobile (view demo here) with three tabs that show transitions. Can you provide guidance on how to achieve the same functionality in Angular? I have been attempting t ...

Experiencing a lack of defined information when using a service

After spending hours trying to figure it out, I have a question. The issue here is that the data is being received faster than my services can load. gen-service function genEmpId() { settingsService.getSettings().then(function (data) { var comId = d ...

Using a Function to Retrieve Styles in React Native for Android

My goal is to dynamically add views based on the data received from JSON. Each event should be represented with a different color: red or blue. The app will insert a view accordingly. class MainPage2 extends Component { constructor () { super() var s ...

Generating an embedded object on the fly using an Angular Directive

After successfully establishing communication between the directive and controller, I am able to populate the embed code without any errors. However, the flash generated by the directive is not functioning at all, despite no visible discrepancies in the HT ...

How can I display a timer icon in front of text on a Material-UI CardHeader subtitle?

I have a question regarding displaying time in my posts. Currently, I am showing the time as 'a few seconds ago', '2mins ago', 'an hour ago', etc. However, I would like to include a clock icon before this string. Although I a ...

The function history.popstate seems to be malfunctioning, as it is triggered by both the forward and backward navigation buttons in

When I press the back button, I am attempting to retrieve the previous state. Upon inspecting, I noticed that the popstate function is also triggered by the forward button. However, it does not revert to the previous state even though the popstate function ...

How can I add a blank selection at the bottom of my ng-options dropdown?

At the moment, my setup looks something like this (in a simplified form): <select ng-model=model.policyHolder ng-options="person.index as person.name for person in model.insurance.persons"> <option value>Someone else </select> This co ...