Ways to manage multiple Observables

Two Observables are being returned from different services, each providing only one value (similar to Observable.just()). In TypeScript, types play a crucial role in this context.

Is there a method to determine when both Observables have been resolved (in terms of promises), whether successful or failed? It is essential to handle failures individually and proceed accordingly.

Here's a hypothetical scenario:

const obs1  = someService.getThisThing(); //Observable<Type1>
const obs2  = someService.getAnotherThing(); //Observable<Type2>

const someObj = {};

obs1.subscribe(v1 => someObj.v1 = v1);
obs2.subscribe(v2 => someObj.v2 = v2);

// Invoke someFunc(someObj) only when both observables above return a value
someFunc(someObj);

I attempted using merge, but encountered the loss of type safety due to unordered values. This approach required me to inspect types within .subscribe.

I also experimented with combine and combineLatest as mentioned here; however, they both resolve simultaneously, leading to a complete failure if even one Observable encounters an error.

Answer №1

If you find yourself needing to address each error separately, you will have to attach catch() (or maybe another operator) to every Observable. Operators like forkJoin() or merge() always trigger an error notification when any of their sources encounter an error.

const Observable = Rx.Observable;

let sources = [
  Observable.of(123).catch((err) => Observable.of('caught error')),
  Observable.throw('error').catch((err) => Observable.of('caught error'))
];

Observable.forkJoin(...sources)
  .subscribe(values => console.log(values));

Check out the live demonstration here: https://jsbin.com/hirodef/3/edit?js,console

The second Observable throws an error that is caught using catch() and substituted with the string caught error.

This demonstration outputs to the console:

[123, "caught error"]

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

What is the best way to configure the default entry point for a package.json file in a React

I'm having trouble with the default export in my package.json file. when I try to import: import { Component } from 'packagename/'; // size 22kb or import { Component } from 'packagename/dist' // size 22kb; but import { Component ...

Accessing the state from a child functional component and then adding it to an array of objects in the parent component

I'm facing a challenge with a parent component that needs to manage the data of its child components stored in an array of objects. My goal is to add new child components and maintain their information within the parent's state as an array of obj ...

Determining if an emitted event value has been altered in Angular 4

I am currently working on an Angular 4 project. One of the features I have implemented is a search component, where users can input a string. Upon submission of the value, I send this value from the SearchComponent to the DisplayComponent. The process of ...

Vue.js enhances user input interactions

CSS <span :style="{ display : displayTitle }" @click="toggleInput()"> {{ text }} </span> <input v-if="isEditing" type="text" v-model="text" @blur="hideInput" @keydown.enter="saveChanges" @keydown.esc="cancelE ...

How can you manage state with ContextAPI and Typescript in a React application?

I seem to be facing an issue that I can't quite figure out. I have experience using ContextAPI without TypeScript, and I believe I'm implementing TypeScript correctly. However, something seems off as nothing happens when I call the setter. My goa ...

Organize your blog content by utilizing post IDs as the designated id attribute

What is the best way to format blog posts and comments in HTML so that I can easily manipulate them later using jQuery/Javascript for tasks like updating, deleting, or making Ajax calls? I am considering using the IDs (primary keys in the database) of the ...

The functionality of the Vueify modal seems to be malfunctioning when incorporating Vueify alongside a central Modal.vue file that houses modal templates

I've been experimenting with integrating this tutorial on creating reusable modal dialogs with Vuejs and adapting it for use with Vueify. Initially, I was able to successfully implement it, but after exploring a different approach briefly, I returned ...

The new and improved Vue 3 computed feature in the Composition API

The temporary object appears as: tmp : { k1: { k2 : { k3 : [abc, def] } } To access k3 in the setup, it should be: tmp.value.k1.k2.k3[0 or 1]. I am looking to change its name to something like - k3_arr = tmp.value.k1.k2.k3; Within my Vue single componen ...

AngularJS factory architecture for multiple functions

It's not the exact data I'm using in my project, but I'm simplifying it for demonstration purposes. In my AngularJS app, I have a factory like this: myApp.factory('inputinfo', function () { var self = { test: function (in) { ...

What is the most efficient way to restrict multiple input fields, each using v-model, to only accept numeric values in Vue.js without duplicating code for every input field?

I have several input fields in Vue.js that I want to restrict to only accept numbers. I want to prevent users from entering any characters except digits from 0-9. I managed to achieve this successfully with a solution that is resistant to copy-paste: C ...

Prevent MUI Autocomplete from closing when the option menu is opened with blur

Seeking assistance with modifying an autocomplete menu to include a dropdown for each item. Issue arises after trying to open the additional menu as it triggers an immediate closure of the autocomplete. For reference, attached is an image showcasing the i ...

What might be the reason for jQuery not functioning in Internet Explorer 11?

Working on developing a slideout menu for my website using jQuery. It functions perfectly in Chrome, but encountering issues in Internet Explorer (IE11). Extensive search hasn't provided a solution yet. Seeking assistance and any help would be highly ...

Navigating through a sequence of URLs in Node.js, one by one

I am new to node js and experimenting with creating a web scraping script. I've received permission from the site admin to scrape their products as long as I make less than 15 requests per minute. Initially, my script was requesting all URLs at once, ...

Subject.next() not triggering Observable on value change

I'm currently working on developing an autocomplete feature using Observable and Subject in Angular. However, I've run into an issue where the service method is not triggered when the Subject object's value changes. Below is a snippet of my ...

Creating one-to-one relationships in sequelize-typescript can be achieved by setting up multiple foreign keys

I have a question about adding multiple foreign keys to an object. Specifically, I have a scenario with Complaints that involve 2 Transports. One is used to track goods being sent back, and the other is used for goods being resent to the customer. @Table({ ...

What potential factors could lead to an MUI Snackbar failing to produce the accurate class names?

I am facing an issue with displaying notifications on my Gatsby blog whenever the service worker updates. I am using a MUI Snackbar toast for this purpose. However, sometimes the styling of the toast is not applied correctly and it ends up looking like thi ...

Error: Trying to access properties of an undefined object (specifically 'promise.data.map')

Currently, I am in the process of writing unit tests for a project built with Angular version 1.2. For my controller tests, I have set up a mockService that returns a deferred promise. One of the service methods looks like this: function getItems() { ...

Configuring the baseUrl for Axios in a Vue.js application triggers the sending of a request

I have encountered an issue in my app where Axios automatically makes a request to the baseUrl without me explicitly making one. This occurs even when the app is loaded in the browser. In my main.js file, I have set the baseUrl using: axios.defaults.baseU ...

Using Vue to handle Promise resolution - incorporating Laravel Gate logic into Vue

Trying to incorporate Laravel's authorization and policy into Vue has been a challenge for me. I'm working on creating a mixin that sends a GET request to a backend controller. The issue I've encountered is that the v-if directive is receiv ...

Discover the art of concurrently listening to both an event and a timer in JavaScript

Upon loading the page, a timer with an unpredictable duration initiates. I aim to activate certain actions when the countdown ends and the user presses a button. Note: The action will only commence if both conditions are met simultaneously. Note 2: To cl ...