Is there a way to merge two observables into one observable when returning them?

I'm struggling with getting a function to properly return. There's a condition where I want it to return an Observable, and another condition where I'd like it to return the combined results of two observables.

Here is an example.

getSearchFeed(): Observable<items[]> {
   if (this.condition) {
     return this.populateItemsArray();            //function Returns Items Array Observable
   } 

   //second condition
   const someItems = this.populateSearch();       //function Returns Items Array Observable
   const otherItems = this.populateOtherSearch(); //function Returns Items Array Observable

   return forkJoin(someItems,otherItems)
    .pipe((res:Array) => {
      return [...res[0],...res[1]];
   });
}

I've seen discussions about merging results from different observables, which I understand how to do by subscribing and joining. My question is more focused on how to return an Observable for the second condition.

Here are some things I've tried,

return forkJoin(someItems,otherItems)
 .pipe(map((res:Array<Observerable<Items[]>>) => {
    return [...res[0],res[1]];
});

and

const source = of([someItems,otherItems]);
const merged = source.pipe(mergeMap( q => forkJoin(...q)));
return merged;

Answer №1

When faced with this scenario, the solution lies in utilizing the RxJS operator called toArray(). As outlined in the official documentation, the purpose of the toArray() operator is to

Collect all emitted values from the source and then emit them as a single array once the source completes.

To implement this approach, your code should follow this structure. By doing so, you will effectively merge the returned observables into a unified array.

import { forkJoin } from 'rxjs';
import { toArray } from 'rxjs/operators';

getSearchFeed(): Observable<items[]> {
   if (this.condition) {
     return this.populateItemsArray();            //function Returns Items Array Observable
   } 

   //additional condition
   const someItems = this.populateSearch();       //function Returns Items Array Observable
   const otherItems = this.populateOtherSearch(); //function Returns Items Array Observable

   return forkJoin(someItems, otherItems)
     .pipe(
       toArray(),
     );
}

Update: Upon realizing the necessity to flatten the returned observables into a singular array, a simpler solution involves using the Array.flat() method within the map operator. This action will effectively flatten the results into one cohesive array.

import { forkJoin } from 'rxjs';
import { map } from 'rxjs/operators';

getSearchFeed(): Observable<items[]> {
   if (this.condition) {
     return this.populateItemsArray();            //function Returns Items Array Observable
   } 

   //additional condition
   const someItems = this.populateSearch();       //function Returns Items Array Observable
   const otherItems = this.populateOtherSearch(); //function Returns Items Array Observable

   return forkJoin(someItems, otherItems)
     .pipe(
       map(res => res.flat(2))
     );
}

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

Show just a single error message if there are two validation errors present

In my AngularJS timepicker, users can choose multiple time segments for each day. The code has validation to detect duplicates and overlapping time segments. For example, entering 11:00am - 12:00am twice will trigger two error messages: 'Overlapping t ...

Creating interfaces within props is essential for defining the structure of components

I'm trying to pass an Interface to one of my components, but I'm running into some issues with my approach. Here's what I have so far: import { InterfaceType } from "typescript"; type Props = { dataType: InterfaceType } export default ...

The idiom 'listen' is not recognized within the context of type 'Express'. Try using a different property or method to achieve the desired functionality

Encountering an error in VS Code while working on an Angular 13 app that utilizes Angular Universal for Server Side Rendering. The specific error message is: Property 'listen' does not exist on type 'Express'.ts(2339) This error occurs ...

Encounter an error message "Expected 0 type arguments, but received 1.ts(2558)" while utilizing useContext within a TypeScript setting

Encountering the error mentioned in the title on useContext<IDBDatabaseContext> due to the code snippet below: interface IDBDatabaseContext { db: IDBDatabase | null } const DBcontext = createContext<IDBDatabaseContext>({db: null}) Despite s ...

Error: TypeScript cannot locate the specified <element> in the VSCode template

After conducting some observations, I've come to realize that the error is specific to the first .tsx file opened in VSCode. Once IntelliSense runs on this initial file, the error appears. Subsequent files work fine without any issues. To troubleshoo ...

`"Type is invalid" error occurring with component after importing it into a different project``

I am currently working on developing a custom Storybook 7 Typescript component library with React. I have successfully imported this library into another project using a private NPM package. However, one of the components in the library, specifically the ...

Using TypeScript for Immutable.js Record.set Type Validation

Currently, I'm utilizing Immutable.js alongside TypeScript for the development of a Redux application. In essence, the structure of my State object is as follows: const defaultState = { booleanValue: true, numberValue: 0, } const StateRecord = ...

Is it possible to toggle between namespace and class using parentheses?

While working with older javascript code, I stumbled upon the following snippet: // module1.js class Class { constructor() { console.log('hello') } } const exported = { Class: Class, } module.exports = exported This code is then ...

Evaluate the Worth of a Property Established in a Subscription

Currently, I am using Jasmine for testing an Angular application and facing a challenge in testing the value of a property that is set within the subscribe call on an Observable within the component. To illustrate this point, I have created an example comp ...

How can I uniquely combine a code with an existing CSS class and make modifications to it?

I am using ngx-skeleton-loader and I would like to change the color, but I am facing some difficulties. Here is an image that illustrates the issue. When looking at the developer tools, you can see the styles action in the styles action bar. .loader ...

A TypeScript function that converts a value into an array if it is not already an array, ensuring the correct type is output

I'm attempting to develop a function that wraps a value in an array if it is not already an array. export function asArray<T extends Array<any>>(value: T): T export function asArray<T>(value: T): T[] export function asArray(value: a ...

Unable to prolong TypeScript document

As I develop a drag and drop interface, upon dropping a file, the native File is retrieved. To enhance this interface with additional information, I decided to explore various approaches. In my initial attempt, I utilized: interface AcceptedFile extends ...

Coloring intersected meshes in three.js will recolor every mesh in the scene

My attempt to change the color of a mesh on mouse hover is not functioning as expected. Instead of coloring only one mesh red, every single mesh is being filled with the color. Upon inspecting the intersected objects during debugging, it shows only one el ...

Steps for executing a single test across multiple URLs using Playwright

My goal is to run a test for over 1000 URLs as quickly as possible. However, I am encountering a timeout error when the number of URLs exceeds 10. It seems like the tests are running sequentially, causing delays. Is there a way to run these tests in parall ...

Issue: An error occurred while trying to parse JSON data in TypeScript due to an undefined 'description' property

Encountering an error message when attempting to retrieve the description attribute from the following Sample Json. Error: TypeError: Cannot read property 'description' of undefined when trying to access json data in typescript import {Age ...

Troubleshooting Angular 14 Custom Form Control Display Issue

I'm facing an issue while attempting to develop a custom form control in Angular 14. Despite no errors showing up in the console, my custom control is not rendering as expected. When inspecting the Elements tab in the console, I can see the parent com ...

Troubleshooting problem with TypeScript observables in Angular 5

Having trouble with a messaging app, specifically an error related to TS. The syntax checker in the Editor is flagging this issue: Type 'Observable<{}>' is not compatible with type 'Observable'. Type '{}' cannot be as ...

Sharing a FormGroup between different components

For my Angular 2+ application utilizing reactive forms, I have a requirement to share the main FormGroup across multiple components. This will allow different sections of the form such as header and footer to be managed independently by separate components ...

Transitioning from ng-repeat filter to Typescript

As I migrate my project from AngularJS to modern Angular 8, one of the steps is converting JavaScript code to TypeScript. During this process, I encountered a challenging issue with the `ng-repeat` filter feature. Initially, my HTML template looked like t ...

Struggle with typescript integration with emotion and styled components

Issue Description: I encountered an issue while working with typescript and emotion/styled libraries. When attempting to specify the type of the parent component that wraps a styled component, I faced difficulties. The scenario involves a parent componen ...