Keep moving forward with RXJS by subscribing to concat after encountering an error

I am facing a challenge with an array of observables that need to fire off sequentially. My goal is for the observer to catch any errors, log them, and continue observing without restarting or completing.

Currently, when an error occurs, the observer stops instead of continuing as desired.

import * as Rx from "rxjs";
const source = [
  Rx.Observable.from("1").delay(200),
  Rx.Observable.from("2").delay(150),
  Rx.Observable.throw("error"),
  Rx.Observable.from("3").delay(124),
  Rx.Observable.from("4").delay(201),
];
let sSource = Rx.Observable.concat(...source);
sSource.subscribe((v) => {console.log(v)}, (e) => {console.log(e)});

Current output:

1
2
error

Expected output:

1
2
error
3
4

We have tried adding individual catch handlers to each observable in the source array but feel there should be a more elegant solution to this problem. If necessary, I can share our current solution.

Answer №1

To handle errors in multiple source observables, you can utilize the catch operator and implement error logging within it. Here's an example:

const sources = [
  Rx.Observable.from("1").delay(200),
  Rx.Observable.from("2").delay(150),
  Rx.Observable.throw("error"),
  Rx.Observable.from("3").delay(124),
  Rx.Observable.from("4").delay(201),
];
const sourcesWithCatch = sources.map(s => s.catch(e => {
  console.log(e);
  return Rx.Observable.empty();
}));
const concatted = Rx.Observable.concat(...sourcesWithCatch);
concatted.subscribe(v => console.log(v));
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://unpkg.com/rxjs@5/bundles/Rx.min.js"></script>

Answer №2

Keep in mind that Rxjs 5 introduces the onErrorResumeNext function which mimics the behavior of the Visual Basic On Error Resume Next statement.

You can find this example in the official documentation.

var source = Rx.Observable.onErrorResumeNext(
  Rx.Observable.just(42),
  Rx.Observable.throw(new Error()),
  Rx.Observable.just(56),
  Rx.Observable.throw(new Error()),
  Rx.Observable.just(78)
);

var subscription = source.subscribe(
  data => console.log(data)
);
// => 42
// => 56
// => 78

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

NGRX Store: Unable to modify the immutable property '18' of the object '[object Array]'

While attempting to set up an ngrx store, I encountered 7 errors. Error Messages: TypeError: Cannot assign to read only property '18' of object '[object Array]' | TypeError: Cannot assign to read only property 'incompleteFirstPass ...

`How can I sort information based on a chosen parameter?`

Is it possible to combine the two conditions into one within the function onSelectedReport()? Representing these conditions in HTML would result in: HTML: <div *ngFor="let report of reports"> <div *ngFor="let i of income"> <di ...

Encountered an issue with the Dynamic Form: TypeError - The property 'value' is undefined and cannot be read

RESOLVED An incorrect value was causing an issue with the onChange function. public onChange = (e:any, key:any) => { this.setState({ [key]: e.target.value }); }; I'm struggling to resolve an error while inputting data into my form in T ...

The type 'string' cannot be assigned to type 'ImageSourcePropType'

Context Attempting to utilize a SVG component in React Native with the xlinkHref property within an Image tag. The SVG file was converted into a React Native Component (TSX) using the tool provided at . While simple SVG icons have been successfully used be ...

Node.js is throwing the error "error TS18003: Config file does not contain any inputs."

I'm encountering an error and need help fixing it. Currently, I am using Windows 11. Every time I attempt to run npm run build in the command prompt, I encounter this specific error: Error File package.json package.json File tsconfig.json "com ...

The issue arises when trying to convert t to a float in TensorFlow within an Angular environment because

I've been working on integrating TensorFlow Facemesh into my Angular application. After importing all the necessary modules and experimenting with different models, I am currently using: import * as tf from '@tensorflow/tfjs'; import * as fa ...

"Transforming a callback function to an asynchronous function results in an error

I have a piece of code that is functioning as expected: var smtpConfig = { host: 'localhost', port: 465, secure: true, // use SSL selfSigned: true }; // create reusable transporter object using the default SMTP ...

Tips for transforming the inner elements of each Object emitted by an observable prior to releasing the overarching observable

As a newcomer to Observables and rxjs, I am seeking assistance in understanding the concept better. I have a function that is triggered when a user clicks to show comments under a blog post. showComments(){ this.firestoreservice.getComments(this. ...

Uncomplicating RxJs Operators: Decoding switchMap and combineLatest

I currently have the following RxJS subscription : combineLatest([obs1$, obs2$]) .pipe( filter(val=>!!val[0] && !!val[1]), // ensuring no null values on both observables switchMap(([val1, val2]) => combineLatest([of(v1), getObs3$( ...

What is the best way to obtain the dimensions of an image in Angular 2 (or newer) before uploading it to the server, and can this be accomplished without utilizing jQuery?

After searching through multiple resources, I realized that most of the solutions are written in jQuery. However, I am specifically looking for a solution in Typescript. The HTML code snippet is as follows: <input #coverFilesInput class="file-input" t ...

Changing the value of an object in Angular can be achieved by utilizing the two

I have a service with the following methods: getLastStatus(id): Observable<string> { let url_detail = this.apiurl + `/${id}`; return this.http.get<any>(url_detail, this.httpOptions).pipe( map(data => { ...

Ways to incorporate type into an object comprised of n element in Typescript

Is there a way to assign types to objects with different keys and values, but where "other" remains constant across all of them? How can this be achieved using TypeScript? { color: "red", size: "small", other: { price: 345 discount: 10 ...

Utilizing Service within Express Router

My journey into the world of NodeJS is just beginning, coming from a .NET background with a love for dependency injection, inversion of control, and microservices. I am now venturing into TypeScript to create services based on my past experiences. Using ex ...

Angular - Dividing Values within Input Arrays

In the input field available to users, they can enter multiple inputs separated by commas. <div class="container"> Enter your values:<input type="text" multiple #inputCheck> <input type="submit"(cli ...

Error in Angular 2 component when loading background images using relative URLs from an external CSS skin

In my angular2 component, I am utilizing a third-party JavaScript library. The skin CSS of the component attempts to load images using relative URL paths. Since I am following a component-based architecture, I prefer to have all component dependencies enca ...

Issue encountered while executing npm install due to rxjs version discrepancy

While developing a new Angular App, I utilized Angular CLI by running ng new. However, when attempting to launch the app with npm start, I encountered the following error: ERROR in node_modules/rxjs/internal/types.d.ts(81,44): error TS1005: ';' ...

Creating TypeScript declarations for the `enhanced-resolve` library: A step-by-step guide

Currently, I am in the process of converting enhanced-resolve to TypeScript. Exploring the New Version The majority of the work has been completed. However, I have encountered a challenge due to the outdated structure of enhanced-resolve. Defining the e ...

Typescript error encountered while attempting to fetch repository from Redis OM

I'm currently working on developing a shopping cart system with the use of expressjs, typescript, and redis OM for the in-memory database. As I created a schema using Redis OM, I encountered an error The error message says: 'Property 'fetc ...

Which rxjs operator emits a single value when any of the source observables emits a value?

Similar to the RXJS operator race, except this should continue emitting without stopping. time -> source1 emits 1 4 source2 emits 2 5 source3 emits 3 6 Therefore, the combined observable should emit t ...

Converting constants into JavaScript code

I've been diving into typescript recently and came across a simple code snippet that defines a constant variable and logs it to the console. const versionNuber : number = 1.3; console.log(versionNuber); Upon running the tsc command on the file, I no ...