Tips for iterating through a monitored list to merge current values from various observables

I am currently working with an observable that streams an array of food items. For each item, I need to retrieve the latest information on the cook, kitchen, and knife used in its preparation. These values are obtained from separate observables like getCookById(food.cook.id).

  • I want to wait for the array of food items to be received
  • Once I have the array, I need to map over each food item and:
    • Retrieve the latest information on the cook, kitchen, and knife (possibly using combineLatest)
    • Combine these values into an object structure like:
  • {
       foodItem,
       cook,
       kitchen,
       knife
    }
    
  • Return an array containing all the transformed items

Currently, my implementation is resulting in an array of empty items:

    const foodObservable = new Subject();
    
    foodObservable.pipe(
      map(foodItems => {
        return foodItems.map((foodItem: any)=>{
          const cookObservable = new Subject();
          const kitchenObservable = new Subject();
          const knifeObservable = new Subject();

          combineLatest(cookObservable, kitchenObservable, knifeObservable).subscribe(([cook, kitchen, knife]) => {
            return {
              foodItem,
              cook,
              kitchen,
              knife
            };
          });
        })
      })
    ).subscribe(foodPreparationArray=>{
      console.log(foodPreparationArray) // array of empty values :(
    })

Answer №1

If you take into account your current situation and the feedback provided, it is recommended to make the following adjustments:

  1. Consider utilizing a higher order mapping operator such as switchMap to map from one observable to another. The map operator is typically used to transform emitted data.

  2. In place of valueChanges(), opting for Firebase's get() may be more suitable in this scenario if immediate value retrieval is required without continuous observation. Additional information can be found here.

  3. By replacing combineLatest with forkJoin, using get() instead of

    valueChanges()</code ensures observables complete rather than continuously stream data.</p>
    </li>
    <li><p>It is advisable to employ two instances of <code>forkJoin
    : The first to initiate requests for each element within the foodItems array, and the second to trigger requests for cook, knife, and
    kitchen</code concurrently.</p>
    </li>
    <li><p>To consolidate the results, leveraging the <code>map
    operator is recommended.

You can try implementing the following code snippet:

foodObservable.pipe(
  switchMap((foodItems: any) => 
    forkJoin(
      foodItems.map((foodItem: any) => 
        forkJoin({
          cook: db.collection('cook').doc(foodItem.cookId).get(),
          kitchen: db.collection('kitchen').doc(foodItem.kitchenId).get(),
          knife: db.collection('knife').doc(foodItem.knifeId).get()
        }).pipe(
          map(({cook, kitchen, knife}) => ({
            ...foodItem,
            cook: cook,
            kitchen: kitchen,
            knife: knife
          }))
        )
      )
    )
  )
).subscribe({
  next: (foodPreparationArray: any) => {
    console.log(foodPreparationArray);
  },
  error: (error: any) => {
    // handle 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

Tips for maintaining the orderby values in IEnumerable despite multiple switch case executions

I am working with a IEnumerable<Cars> variable where I store values from the database. My goal is to enable sorting based on user input for this variable. The UI displays columns such as Car Model, Car Model's year, Number of car sold out, and ...

Establishing a Recyclable Testing Rendering Method in redux toolkit version 2

In the era of Redux Toolkit v2, a noticeable change occurred with the absence of the EmptyObject type and the unavailability of the PreloadedState type in the @reduxjs/toolkit package. This has led to a requirement of defining all reducers inside the pre ...

Ensure that the HTML history is cleared when the page is refreshed after being modified with

My application stores an array of states with the index in history.state, which works fine. However, when I go back to the first page and refresh, the array is gone (as expected), but the forward history state remains. Is there a way to remove the fake hi ...

specialized registration process with auth0 in Angular

I am attempting to enhance the user information in a single call. The process involves first signing up with a username and password on Auth0, followed by adding additional userinfo to the database during the callback phase. However, I am encountering diff ...

What is the correct way to send a GET request in angular?

Trying to make a GET request from Angular to Spring Java, but encountering error code 415 zone.js:3243 GET http://localhost:8080/user/friend/1 415 Below is my Spring Java code for the endpoint: @RequestMapping( value = "/friend/{idUser}", ...

Implementing Node.js with the functionality to replace content in templates

My current task involves creating offer letters for employees, and I have a default template named index.html: index.html <!DOCTYPE html> <html> <head> </head> <body> <div id="header"> <h1>Offer Letter</h1> ...

JSX parsing is not supported by Webpack

Recently, I started delving into webpack and react. While troubleshooting a particular issue, I noticed that the solutions I came across didn't quite fit my scenario; they were mainly related to missing dependencies or incorrect webpack config file fo ...

Creating a return type for JSON observables in Angular 2 by defining it as an interface or

I want to ensure that my JSON API response is easily organized into a class or interface so that I can always identify the attributes present. The JSON data I am working with is as follows: { "users": [ { "id": "bd3d70fd-03f7-4f5e-9ac1-4cb7221 ...

Is there a way to retrieve the object in JSON format using either jQuery or JavaScript?

I'm just starting to learn about JSON Is there a way to showcase specific data in HTML? For example, I'd like to display the 'lat' and 'lng' values from the 'southwest' section or maybe show the 'text' val ...

How can I handle the different data type returned by ReactDom.render?

My main focus is on rendering Markdown. Additionally, I also need to parse HTML which is passed as a string. In this scenario, children represents the HTML passed as a string, while isParseRequired indicates if parsing is needed. import cx from 'clas ...

Authenticate users using JavaScript usernames

Below is my registration link that opens a modal: <a href="#registermodal" data-toggle="modal">Register Here</a> Here is the code for the modal dialog: <div class="modal fade" id="registermodal" role="dialog" style="overflow: scroll;"> ...

Implement a dropdown menu for filtering, but it is currently not functioning as expected

When I select a city_name, my goal is for the graph to only display information pertaining to that particular city. In the params section of my code, I have included filtering options using a selection menu in Vega-Lite. However, despite selecting Brisba ...

Generate a D3.js vertical timeline covering the period from January 1, 2015 to December 31, 2015

I am in need of assistance with creating a vertical timeline using D3.js that spans from the beginning of January 2015 to the end of December 2015. My goal is to have two entries, represented by colored circles, at specific dates within the middle of the t ...

Which specific HTML5 video event is triggered when the current playback time of the video is updated?

My goal is to give users the option to skip the preroll ad after a specified time (e.g. 5 seconds into the ad) and then transition to playing the regular video content. How can I make this happen? Below is an outline of my current approach: var adManager ...

Display sibling element upon hovering with AngularJS

Within a single view, I have multiple instances of repeated content elements. Each content element contains an anchor element. My goal is to toggle a class on a sibling element within that specific content element when a user hovers over the anchor. For c ...

Combine two arrays without changing the number of elements in each array

My task involves combining array A with array B in a way that preserves the original number of indices in array B. For example: const array_A = [1, 2, 3, 4]; const array_B = [0, 0, 0, 0, 0, 0, 0]; The desired output would be: const result = [1, 2, 3, 4, ...

What is the process for transferring a function to reducers in Redux Toolkit?

In one of my files called Main.tsx, I have a function that sends a request and retrieves data: async function fetchProducts(productsPage = 1, id?: number) { const itemsPerPage = 5 let url: string if (id) { url = `https://reqres.in/api/ ...

Exploring the World of 3D Curve Geometry with Three.js

I am working with an array of Vector3s that represents a curved shape in 3D space. While I have successfully rendered an outline of the curve in Three.js using THREE.Geometry and THREE.Line, I am now looking to fill it with color. My attempts to use THREE ...

What is the best way to utilize the $('input').on('change', function() method within AngularJS?

I am working on creating a registration form page using AngularJS and I need to display the percentage completed. The form consists of over 50 fields, so I am looking for a simple way to implement this functionality. Below is a snippet of the code I have ...

What is the process for determining the total of elements within an array?

Imagine you have the following array: const items = [ { "amount1": "100", "amount2": "50", "name": "ruud" }, { "amount1": "40", "amount2": "60", "name": "ted" } ] Your goal is to calculate the sum of all amount1 and amount ...