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

The subscription function in observables may result in values that are undefined

I integrated a new angular 2 library into my application called "angular2-grid". This library is located within the node_modules folder. Furthermore, I created a service as shown below: import { Injectable } from '@angular/core'; import { Htt ...

Utilize Knex to retrieve data from the req.query

express and knex have been giving me some trouble; I am struggling to get this endpoint working using req.querys (response from express), even though it worked fine when I used req.params. Express: app.get(`/actor`, async (req: Request, res: Response) =&g ...

Attempting to invoke a TypeScript firebase function

I'm currently working on incorporating Firebase functions in my index.ts file: import * as functions from "firebase-functions"; export const helloWorld = functions.https.onRequest((request, response) => { functions.logger.info(" ...

Tips for testing nested subscribe methods in Angular unit testing

FunctionToTest() { this.someService.method1().subscribe((response) => { if (response.Success) { this.someService.method2().subscribe((res) => { this.anotherService.method3(); }) } }); } Consider the following scenario. ...

Utilizing the power of Typescript in Express 4.x

I'm currently working on building an express app using TypeScript and here is what my code looks like at the moment: //<reference path="./server/types/node.d.ts"/> //<reference path="./server/types/express.d.ts"/> import express = requir ...

A property in TypeScript with a type that depends on the value of an object

How can we troubleshoot the error not displaying in Typescript and resolve it effectively? Explore Typescript sandbox. enum Animal { BIRD = 'bird', DOG = 'dog', } interface Smth<T extends Animal = Animal> { id: number; a ...

"Implementing a date picker in your Ionic 5 app: A step-by-step

How can I integrate a date picker similar to the Angular Material Date picker into my Ionic 5 application? I prefer not to use the native ion-datetime component due to limitations such as incomplete calendar display and lack of support for alternative ca ...

Unable to retrieve the updated value from the service variable

I'm attempting to implement a filter that allows me to search for items based on a service variable that is updated with user input. However, I am only able to retrieve the initial value from the service in my component. Service HTML (whatever is typ ...

Can someone please explain how to prevent Prettier from automatically inserting a new line at the end of my JavaScript file in VS Code?

After installing Prettier and configuring it to format on save, I encountered an issue while running Firebase deploy: 172:6 error Newline not allowed at end of file eol-last I noticed that Prettier is adding a new line at the end when formatting ...

Simple method for wrestling with objects in TypeScript HTTP POST responses

Can anyone help me understand how to extract information from an object received through an HTTP POST request? Below is the code I am using: this.http.post(url, user, httpOptions).subscribe(result => { console.log(result.status); }); The issue aris ...

Ways to imitate an export default function

//CustomConfigurator.ts export default function customizeConfig(name: string): string { // add some custom logic here return output; } //CustomUtility.ts import customizeConfig from './CustomConfigurator'; export default class CustomUtility ...

The RouteParams encounter a problem because it is unable to resolve all parameters

I'm encountering an issue with the RC3 router. The error message I am receiving is: Can't resolve all parameters for RouteParams: (?). Below is my code: //route.ts import {provideRouter, RouterConfig} from '@angular/router'; import {H ...

What is the best way to implement a dynamic back button in Next.js?

Being familiar with creating a standard back button, I am now eager to craft one that directs the user back by one step in the URL rather than returning to the previous page. This way, I can utilize the button in various locations without needing to alter ...

Connecting HTML to an AngularFirestore collection using snapshotChanges

In my mobile app, I am using AngularFirestore2v5/rxjs to connect a hybrid Ionicv3/Angularv4 app to a Firestore collection. While binding UI with AngularFirestore.valueChanges works fine, switching to snapshotChanges for retrieving the id is causing some is ...

Using Bazel, Angular, and SocketIO Version 3 seems to be triggering an error: Uncaught TypeError - XMLHttpRequest is not recognized

Looking to integrate socket.io-client (v3) into my Angular project using Bazel for building and running. Encountering an error in the browser console with the ts_devserver: ERROR Error: Uncaught (in promise): TypeError: XMLHttpRequest is not a constructor ...

Leverage the power of ssh2-promise in NodeJS to run Linux commands on a remote server

When attempting to run the command yum install <package_name> on a remote Linux server using the ssh2-promise package, I encountered an issue where I couldn't retrieve the response from the command for further processing and validation. I' ...

In search of assistance with resolving a React Typescript coding issue

I need help converting a non-TypeScript React component to use TypeScript. When attempting this conversion, I encountered the following error: Class 'Component' defines instance member function 'componentWillMount', but ext ...

React Router malfunctioning on production environment when integrated with an Express backend

My Single Page application is built using React for the frontend and Express for the backend. Within the application, there are two main components: and . The goal is to display the component when the "/"" URL is requested, and show the component for an ...

The function cannot be called on a type that does not have a callable signature. The specified type, 'number | Dispatch<SetStateAction<number>>', does not have any compatible call signatures

Currently, I am working on setting up state to be passed through context in React using hooks. However, when I attempt to use the dispatched state updater function, an error is thrown: Cannot invoke an expression whose type lacks a call signature. Type &a ...

Issues with executing code within the react package for Yahoo Finance 2

I am currently in the process of developing a React application using Vite. The purpose of my app is to retrieve stock-related information from Yahoo using the yahoo-finance2 package. Interestingly, when I run the code as a standalone JavaScript file, eve ...