Looking to leverage RxJs 6 GroupBy for stream organization? Interested in consolidating emissions from various Grouped Observables?

Input Observable stream: The information is retrieved from an observable stream, which stems from a REST request for various projects. This data is obtained in the form of Observable<Project[]>.

     const project1: Project = {
        id: 1,
        title: 'zebra',
        rootId: 1,
      }
    
      const project2: Project = {
        id: 2,
        title: 'algebra',
        rootId: 2,
      }
    
      const project3: Project = {
        id: 3,
        title: 'Bobcats',
        rootId: 1,
      }
    
      const project4: Project = {
        id: 4,
        rootId: 2,
      }
    
      const project5: Project = {
        id: 5,
        title: 'Marigolds',
        rootId: 1,
      }
    
      const project6: Project = {
        id: 6,
        title: 'whatever',
        rootId: null,
      }
    
      const project7: Project = {
        id: 7,
        title: 'peppercorns',
        rootId: null,
      }
    
    let groupProjects: Observable<ProjectSummary[]> 
= retrieveGroupedProjects(of([project1, project2, project3, project4, project5, project6, project7]]));
    
      retrieveGroupedProjects(projects$: Observable<ProjectSummary[]>): Observable<ProjectSummary[]> {
        const timer$ = timer(5000);
        const gatheredData = projects$.pipe(takeUntil(timer$), flatMap(projects => projects));
        const segregatedObservables = gatheredData.pipe(
          groupBy(projects => projects.rootId),
          tap( a => console.log('grouped by:' + a.key))
        );
        const mergedResults = segregatedObservables.pipe(
          mergeMap(a => a.pipe(toArray())),
          shareReplay(1),
          tap( a => console.log('final results:' + JSON.stringify(a)))
        );
        return mergedResults;
      }

The expected output is:

Object{  //Root of 1
  id: 1,
  title: 'zebra',
  rootId: null
}
Object{
  id: 3, //child of 1
  title: 'Bobcats',
  rootId: 1
} 
Object{
  id: 5, //child of 1
  title: 'Marigolds',
  rootId: 1
}
Object{
  id: 2, //root of 2
  title: 'algebra',
  rootId: 2
}
Object{
  id: 4,  //child of 2
  title: 'dogs',
  rootId: 2
}
Object{
  id: 6,  //unaffiliated
  title: 'whatever',
  rootId: null
}
Object{
  id: 7, //unaffiliated
  title: 'peppercorns',
  rootId: null
}

The condition specifies that groups assigned with a rootId should be displayed before their children (children come after their root) and unattached instances are grouped together. Root elements are recognized when id = rootId, child elements are identified when rootId != null && id != rootId. Unattached instances have a null root id.

Currently, only the final group is being broadcasted. Is there a way to return an observable that transmits all groups and maintains the correct sequence? --appreciate it

Answer №1

When dealing with streams of objects, the groupBy function emits a single group once the stream completes. However, if you are working with streams of arrays, you should use scan instead. Scan functions like reduce but emits each time the source stream emits, rather than just at the end.

It seems like I may not fully grasp what you are trying to accomplish with your question, but this code snippet should help you get started:

sourceThatEmitsArrays.pipe(
  scan(
   (results, emittedArray) => functionThatAddsEmittedArrayToResults(results, emittedArray),
   [] // Start with an empty array
  )
)

This works similarly to a traditional reduce function on arrays, but it emits results every time the source emits.

The functionThatAddsEmittedArrayToResults would look something like this:

(results, array) => array.reduce(
  (newResults, current) => {
    const group = findCurrentGroupInNewResultsOrCreateNewGroup(newResults, current);
    replacePreviousGroupInResultsOrAddTheNewOne(newResults, group);
    return newResults;
  },
  results // Start with previous results
)

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

Exploring the beauty of ASCII art on a webpage

Having trouble displaying ASCII art on my website using a JavaScript function, the output is not as expected... This is how it should appear: https://i.sstatic.net/MCwPb.png And here is the code I am trying to implement for this purpose: function log ...

The Issue with My Ajax Request Not Working When Clicking an Icon

When I click on an icon, I want to trigger an AJAX call. Script.js $('.user-status').click(function() { var userId = this.id; var userStatus = $(this).attr('data-status'); alert('clicked'); $.ajax({ t ...

What is the appropriate content-type to use when sending AJAX POST data?

Having an issue sending base64 image data using ajax post. I suspect the problem lies with the Content-Type value, as I have tried using application/json, text/json, and image/jpeg without success. Javascript function sendFormData(fD) { var urls = fD ...

Having trouble with Javascript fetch() not receiving the correct JSON data from the local server

My Django backend is serving JSON data, but I'm encountering some unexpected results. When using curl 127.0.0.1:8000/posts/, the response includes: [ { "title": "This is a title", "body": "Body :)", "pub_da ...

Troubleshooting the pushstate back function in HTML5 and jQuery

In my code, I have implemented an ajax call to load content dynamically. I am now looking to add a deeplinking effect, and after researching, I discovered that only raw coding can achieve this. Here is what I have implemented so far: jQuery("#sw_layered_c ...

Assistance with designing in JavaScript and Python

Currently, I have a setup where my external website is extracting data from an iframe within our internal company intranet using Javascript. The extraction process is successful, but now I am faced with the challenge of accessing this harvested data in ord ...

The callback function for ajax completion fails to execute

My current framework of choice is Django. I find myself faced with the following code snippet: var done_cancel_order = function(res, status) { alert("xpto"); }; var cancel_order = function() { data = {}; var args = { type:"GET", url:"/exch ...

Issue with Laravel 5.7 Autocomplete search: JavaScript unable to recognize the specified route

I've been following a tutorial on this video: https://www.youtube.com/watch?v=D4ny-CboZC0 After completing all the steps, I encountered an error in the console during testing: jquery.min.js:2 POST http://apr2.test/admin/posts/%7B%7B%20('autocom ...

Why is My JQuery Button Data Null?

I am facing an issue with a button where I want to pass the HTML object as a parameter to a JavaScript function. The objective is to print the data-hi attribute value from the element in the button. HTML BUTTON <button type = "button" onclick = "whoIs ...

mat-tab-group - Positions elements in the center, right, and left for optimal alignment

Is it possible to align the buttons in a mat-tab-group to the left, center, and right positions? I am using mat-tabs. How can I have elements with "left" align to the left, elements with "center" in the center, and elements with "right" align to the right? ...

setTimeout executes twice, even if it is cleared beforehand

I have a collection of images stored in the img/ directory named 1-13.jpg. My goal is to iterate through these images using a loop. The #next_container element is designed to pause the loop if it has already started, change the src attribute to the next im ...

Using the Composition API in Vue 3: Guide to invoking a method within the template to retrieve a return value

Within my template, I have implemented the following code snippet: <template> {{ getScope(scope.row, itemIn.field) }} </template> For the Option API section, I've included: methods: { getScope(data, key) { const str ...

What are some techniques to enhance security when transmitting variables through a URL in JavaScript?

Instead of passing variables through a URL, I am considering implementing a method where the parameters are sent to the popup window through variables once it is opened. This would add an extra layer of security by not exposing sensitive information in the ...

Tips for utilizing the setInterval function in javascript to update the background color of the body

Currently, I am tackling a project for my course and I am seeking to modify the body's background color on my website randomly by leveraging the setInterval technique in my JavaScript file. Any suggestions on how to achieve this task? ...

Tips on transferring key values when inputText changes in ReactJs using TypeScript

I have implemented a switch case for comparing object keys with strings in the following code snippet: import { TextField, Button } from "@material-ui/core"; import React, { Component, ReactNode } from "react"; import classes from "./Contact.module.scss" ...

The Angular project was functioning properly when tested locally, but encountered an error in the Quill Editor during the building process

I have encountered an issue when deploying my Angular 8 + Quill project. Everything works fine locally with 'ng serve', but upon deployment, I am facing the following error. Despite trying various solutions like updating Angular or deleting &apos ...

Triumph with AJAX and jQuery, yet nothing altered

Recently, I came across a situation where I was reading a text file from the local WAMP server. I tried making some changes to this text and then attempted to send it back to the file. However, even though the AJAX request triggered the success function, ...

JavaScript pause until the DOM has been modified

My current situation involves using a JavaScript file to make changes to the DOM of a page by adding a navigation menu. Following this code, there is another function that further modifies the newly added navigation menu. However, I am facing an issue wher ...

retrieve the documents that correspond to a specific string in mongoose

Currently, I am working on integrating a search feature into a MERN stack application. The idea is to utilize the searchWord extracted from req.params.searchWord and fetch results containing that specific searchWord. Although my existing code serves its p ...

The Collada model in Three.js appeared completely dark until a mouse movement brought in some light

Recently, I've run into a peculiar issue while trying to display a collada model in three.js. It appears that there may be an error in the script logic, but I'm having trouble pinpointing it. The problem is that when the page first loads, the Col ...