Execute an asynchronous task on a collection of objects received from an observable source

I've been struggling a bit with the RxJS Observable.

Here's the scenario:

There's an interface (just for clarity) for my objects:

interface MyObject
{
    value: number;
    new_value?: number;
}

Next, there's a small function that takes an object and returns an observable to update the object:

let updateObject = (object: MyObject) => {
    return Observable.create(observer => {
        setTimeout(() => {
            object.new_value = object.value * 5;
            observer.next(object);
            observer.complete();
        }, 1500);
    });
};

Now I have a source observable that returns an array of objects (e.g., as a response from a server):

let observable = Observable.of<MyObject[]>([
    {value: 1},
    {value: 2},
    {value: 3}
]);

So, my goal is to update each object in the array using my "updateObject()" method. When I subscribe to the observable, I expect this result:

// here the asyncOperation should be applied to the observable
observable.subscribe((objects: MyObject[]) => {
    // objects should be:
    // [
    //     {value: 1, new_value: 5},
    //     {value: 2, new_value: 10},
    //     {value: 3, new_value: 15}
    // ]
});

I know it's possible by nesting multiple observables, concatenating them, and subscribing, but I find it messy. I haven't found an existing observable function provided by the RxJS library, so I'm turning to you guys for help!

Do you have any suggestions or solutions for me?

Thank you!

Answer №1

To easily ensure that all inner Observables complete before proceeding, you can simply utilize the Observable.forkJoin method:

observable
  .concatMap((items: MyItem[]) => {
    const observables = [];
    items.forEach(item => observables.push(updateItem(item)));

    return Observable.forkJoin(observables);
  })
  .subscribe(...);

Answer №2

Combining three Observables using merge and then manipulating the values with a timer function to create new values based on the old ones.

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 steps can be taken to resolve the issue of 'modal bootstrap not being defined?

Looking to implement a modal for popups, but encountering an issue with the ng ///appmodule/appcomponent host.ngfactory.js on this page (which currently appears empty). user.html <div> <button data-toggle="modal" mat-raised-button="primary" ...

Is there a way to retrieve the requested data in useEffect when using next.js?

As a newcomer to next.js and TypeScript, I am facing an issue with passing props from data retrieved in useEffect. Despite my attempts, including adding 'return scheduleList' in the function, nothing seems to work. useEffect((): (() => void) = ...

Removing Firebase Users using Angular2/Ionic2

I'm currently working with Ionic2/Angular2 and I've been searching for a guide on deleting users from Firebase. If anyone has any useful examples, I would greatly appreciate the assistance. Thank you. ...

Securing WebAPI Actions with Token-Based Authentication in Angular 2/4/5

I'm looking for guidance on how to securely call a WebAPI action method in Angular FrontEnd after obtaining a token. In my login component code, I store the user token in local storage after submitting the username and password, then proceed to naviga ...

The PhpStorm code completion feature is not functioning properly when working with TypeScript code that is distributed through NPM

I am facing an issue with two NPM modules, which we will refer to as A and B. Both modules are written in TypeScript and compile into CommonJS Node-like modules. Module B has a dependency on module A, so I have installed it using the command npm install ...

Is there a way to dynamically assign values to [routerLink] based on the elements in an array?

Looking to create a dynamic routing within my template. The routing values are sourced from an array that is being iterated through with ngFor. Additionally, I need to perform some transformations on these string values. Any help would be appreciated. En ...

Encountering build issues after transitioning from Angular version 9.17 to 9.19

After upgrading from Angular 9.17 to 9.19, my ng build process started failing with an error related to variable declaration in both @types/node and zone.js: ERROR in node_modules/@types/node/ts3.5/globals.global.d.ts:1:13 - error TS2403: Subsequent varia ...

What is the best way to showcase one object per day when I have an array of 30 objects in Ionic 4?

I'm looking to showcase a different quote in my app every day for 30 days using an array of 30 quotes. How can I achieve this daily quote rotation in Ionic 4? ...

Is it possible to maintain the Spring default login page while turning off CSRF protection?

I have been working on a Spring+Angular site and the default login page was functioning well for me initially. The issue arose when I needed to turn off CRLF validation to be able to make POST requests from my Angular application, so I disabled it. Unfor ...

What are some alternatives to using multiple slot transclution in an Angular 1.5 component?

In the process of constructing a panel component using angular 1.5, I am looking to embed some markup into this template (which has been simplified): <div class="panel"> <h1>{{ $ctrl.title }}</h1> <div ng-transclu ...

An error was triggered in Apollo GraphQL due to a custom GQL scalar type that includes a regular expression test function

When developing a GraphQL custom scalar in TypeScript, I am working on implementing the serialize/parseValue/parseLiteral functions. In order to match incoming values against a regex, I tried using if (value.test(yearMonthDayRegex)) {} as a condition, but ...

Is there a way to set a custom port number for an Angular application?

I am currently in the process of constructing an Angular application. The application is designed to communicate with a server via HttpClient. However, each time the application connects to the server, it utilizes a different port. I am interested in confi ...

Showing the Name of Fields from the Array of Objects using Angular

Looking to extract only the column names present in each row of an array For example, from the console: this.GobalTableDataSets (3) [{…}, {…}, {…}] 0: {centerName: "--", batchName: "MentorSchedule_5D5C", scheduleStartDate: "20-Nov-2019 14:38:17", s ...

Tips for utilizing the date-formatter feature of bootstrap-table with Angular 2

Hello there! I have integrated the bootstrap-table library with Angular4, but I am facing an issue with the date-formatter feature. Here is the HTML code snippet: <table id="table" data-show-refresh="true" data-show-toggle="true" data-show-columns="tr ...

How can you verify the data type of an object without resorting to type guarding

I have a situation where I need to deal with different types of objects. export interface A { links: number name: string } export interface B { cat: boolean name: string } Initially, I considered using this method: const IsTypeB = (obj: any): obj ...

The installation of @angular/router seems to have encountered an error

I am attempting to update my @angular/router dependency from version 2.0.0 to 3.0.0-alpha.7. I have included it in my package.json file. { "name": "angular2-quickstart", "version": "1.0.0", "scripts": { "start": "tsc && concurrently &bs ...

mat-list-option (click) event without actually choosing the item

At the moment, mat-list-option allows for binding a click event, however it doesn't distinguish between (click) and the default select action. Even utilizing $event.preventDefault() or $event.stopPropagation() will not provide a solution. Clicking on ...

swap out a single amchart for a different one

Here's the current amchart I have: https://i.sstatic.net/J8QLl.png I'm looking to create another amchart with the same data. Essentially, I want to replace the existing graph. You can find the new chart here -> This is my Angular code: pre ...

TS2531: Nullability detected in object when using .match() method

I'm encountering a linting error on fileNameMatches[0] in the following code snippet. Strangely, the error doesn't appear on the Boolean() check. Even if I remove that check, the issue remains unresolved. Can anyone suggest a solution? protected ...

Potential absence of object in strict mode

I have encountered the error message Object is possibly null in typescript specifically for the event handler below, while other event handlers I've written do not trigger this error: <input type="file" className="hide" ...