Combine a list with an observable list

Consider having 3 different types of lists - two basic lists and one observable list.

The challenge arises when you need to combine a non-observable list with the observable one.
The current approach may seem unconventional for observables.

listToMerge = []
listObs$: BehaviorSubject<[]> = new BehaviorSubject([]);
listObsCopy = []

Elements have already been added to the listObs using the next method

listObs$.next(someStuff);
listObsCopy = somestuff;

Below is an attempt to merge them together.

listToMerge = listObsCopy.concat(someOtherStuff);
listObs$.next(listToMerge as any);

Answer №1

Are you in search of a solution that merges all arrays into one using RxJS? Check out the code snippet below!

    import { BehaviorSubject, merge } from 'rxjs';
    import { concatAll, take, tap, toArray } from 'rxjs/operators';

    // Subject (and Observable with take(1) to ensure completion.)
    let listSubject: BehaviorSubject<string[]> = new BehaviorSubject<string[]>(['B1', 'B2']);
    let listObs$ = listSubject.asObservable().pipe(take(1));

    // List to Merge 
    let listToMerge = ['1', '2'];

    let mergedObs$ = merge(listToMerge, listObs$).pipe(concatAll(), toArray());

    mergedObs$.subscribe((value) => console.log('merged array:', value));

https://stackblitz.com/edit/typescript-ukxwep?file=index.ts

The key lies in utilizing the concatAll() operator to flatten the arrays and then employing the toArray() operator to consolidate them into a single array.

It's worth noting that I've included take(1) in the observable for the subject. The subscription will only commence once the Observable is completed.

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

Creating a user-friendly interface for an array of objects, complete with an included array containing those same objects

I have an array that I want to iterate through. It contains a single object and an array of objects. How can I create an interface for this structure? What is the appropriate declaration to replace any[]? Here is the code: export const initialPhotoProps: ...

Updating the useState() function in React when the value changes can be done by utilizing the

I'm struggling to update the count value in my React project. Within my dynamic set, I aim to display the size of the set whenever it changes! My goal is to continuously update the count variable to match ratedSet.size whenever the set's size c ...

Issues with MEAN stack post method not updating database records

I'm having trouble passing data via HTTP post method and seeing the changes reflected in the database. This is the code snippet: addJobList(jobitem) { let headers = new Headers(); headers.append('Content-Type','application/json ...

Encountering an error stating 'Chart name not found' while attempting to utilize chart.js

For days now, I've been struggling with an annoying issue in chart js. I've tried every possible solution but have not been able to figure it out. The problem arises from using a TypeScript environment with ES modules. I attempted to import Char ...

Challenges with date formatting arise for Spanish speakers when the date returns as NaN or an Invalid

I have been working on an Angular app Objective: My aim is to allow users to input dates in Spanish format (DD/MM/YYYY) and display them as such, while converting them back to English format when saving the data to the Database. Issue: One problem I enco ...

Update information in a completely responsive manner through the angular async tube

I'm feeling a bit embarrassed asking this question because I believe I might be overlooking something important. Despite spending a lot of time searching and researching, I only seem to come across complex solutions that involve subjects or behaviorsu ...

Tips for handling various mandatory fields for two different user roles within a unified userModel.ts file on a Next.js and MongoDB user registration API platform

Could you please review my code and provide any suggestions for improvement? I have two types of user roles, candidate and business, each with multiple unique fields. My goal is to consolidate all these fields into one userModel.ts file. import mongoose ...

Is it possible to directly parse a multipart/mixed response without needing to first convert it into a string?

My current challenge involves receiving a multipart/mixed response over HTTP that includes JSON data and PDFs in byte format. Due to Angular's limitations with handling such responses, I have resorted to converting the response into a string using the ...

What is the best way to organize checkboxes (either checked or unchecked) within a mat-table?

https://i.stack.imgur.com/cDQY7.png <ng-container matColumnDef="scheduled"> <th mat-header-cell mat-sort-header *matHeaderCellDef> Scheduled </th> <td mat-cell *matCellDef="let station"> ...

Parent Class implementation for dynamic loading of components

I have been working on creating a new code for dynamic component loading using a parent-child relationship. The child component is set to override the parent and will be used for dynamically loading components. I found this useful link that guided me throu ...

How can we correctly extract a value from the callback of an asynchronous function within another asynchronous function in Angular 6?

I am currently facing an issue with my HTTP provider where I need to access a token value stored in local storage during a GET request. The token value is retrieved using another provider through the getToken function in the HTTP provider. However, I am un ...

Something went wrong in the prerender.ts file at line 7. The error message is indicating that it cannot locate the module './dist-prerender/main.bundle'

Encountering an error while compiling the Angular code for prerendering: ERROR in prerender.ts(7,62): error TS2307: Cannot find module './dist-prerender/main.bundle' npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! [email protected] b ...

There is a lint error that is thrown when upgrading the typings file for JQuery version 3.2

I recently encountered an issue in my application where I used the following interface. It worked perfectly with jQuery 2.0: interface JQuery{ data(key: any): any; } However, upon upgrading to jQuery 3.2, the following lint errors were thrown: All decla ...

Is it possible for me to use ts files just like I use js files in the same manner?

So I recently stumbled upon TypeScript and found it intriguing, especially since I enjoy adding annotations in my code. The only downside is that I would have to change all my .js files to .ts files in order to fully utilize TypeScript's capabilities. ...

What are the steps to transpile NextJS to es5?

Is it possible to create a nextjs app using es5? I specifically require the exported static javascript to be in es5 to accommodate a device that only supports that version. I attempted using a babel polyfill, but after running es-check on the _app file, ...

I am confused about the term "can only be default-imported using the 'esModuleInterop' flag", could you explain it to me?

I ran into a puzzling error: lib/app.ts:1:8 - error TS1259: Module '"mongoose-sequence"' can only be default-imported using the 'esModuleInterop' flag and it seems to be related to this line of code: import _ from 'mongoose-sequ ...

Error: Cannot find property 'bodyParser' on object of type 'e'

I'm interested in incorporating TypeScript into my Node/Express environment and hosting it on the Cloud 9 IDE. However, I've encountered a problem while trying to compile app.ts as the compiler is showing several errors, one of which states "Pro ...

Prior to the loading of the AppModule in Angular, make sure to load

Consider the following situation (Angular v7): Retrieve configuration settings (API server URL and Auth server URL) from an external source (JSON), prior to loading the AppModule Provide configuration to the AppModule (OAuth2 module) Compile the applicat ...

Conceal object from inventory upon clicking

As someone who is new to React and Typescript, I am facing challenges in understanding how to hide a ticket from the list when the hide button is clicked. displayTickets = (tickets: Ticket[]) => { const filteredTickets = tickets.filter(t => ...

typescript locate within the union type in the mapping expression

Consider the following: type X = { label: 'Xlabel', X_id: 12 }; type Y = { label: 'Ylabel', Y_id: 24 }; type Z = { label: 'Zlabel', Z_id: 36 }; type CharSet = X | Y | Z; I am looking for type CharSetByLabel = Map<CharSet& ...