"Learn the trick of converting a stream into an array seamlessly with RxJs.toArray function without the need to finish the

In order to allow users to filter data by passing IDs, I have created a subject that can send an array of GUIDs:

selectedVacancies: Subject<string[]> = new Subject();
selectedVacancies.next(['a00652cd-c11e-465f-ac09-aa4d3ab056c9',
                         'f145b6a6-0a66-49d6-a2d2-eb9123061d96']);

I have another observable that subscribes to this subject and waits for the data (availableVacancies and availableVacancyTypes are Observables from my Angular service):

filteredVacancyTypes: Observable<VacancyTypeModel[]>;
filteredVacancyTypes = this.selectedVacancies
     .flatMap(vacancyIds => vacancyIds)
     .filter(id => !isNullOrUndefined(id))
     .flatMap(id => this.availableVacancies.first(v => v.id === id))
     .flatMap(v => this.availableVacancyTypes.filter(vt => vt.id === v.type.id))

I want to gather the filtered data and return it as an array of VacancyTypeModels. Although I am aware of the toArray method, I cannot use it because the subject is never completed (since I need to wait for more IDs to be published by the user).

Is there any way to return the data as an array without completing the source?

Answer №1

Building up a collection of items becomes simple thanks to the scan operator:

filteredVacancyTypes = this.selectedVacancies
  .scan((acc, arr) => [...acc, ...arr], [])
  .flatMap(vacancyIds => vacancyIds)
  ...

The scan function outputs each interim result. It can also be applied later in the process after all necessary operations have been performed:

filteredVacancyTypes = this.selectedVacancies
  .flatMap(vacancyIds => vacancyIds)
  ...
  .scan((acc, val) => [...acc, val], [])

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

Reaching the maximum request threshold

Currently, I am facing an issue where users are able to upload files from the client side (using Angular 4) to the server (implemented with Spring Boot). The problem arises when a user attempts to upload more than 6 files at once. In such cases, Chrome uti ...

Displaying ASP.Net Core Application on local IIS - Unable to locate content

I started a new project in Visual Studio Code by running the following command: dotnet new angular --use-local-db Afterwards, I upgraded Angular from version 8 to 10 and completed the project. To test it, I used dotnet watch run Everything was running ...

Tips for solving a deliberate circular dependency in an angular provider

If the existing injection token for this provider is available, I want to use it. Otherwise, I will use the specified provider. Below is the code snippet: providers: [ { provide: DesignerRecoveryComponentStore, useFacto ...

Why did the compilation of Next.js using TypeScript and ESLint succeed despite encountering errors?

I've been delving into Next.js and encountered unexpected results when integrating TypeScript and ESLint. ESLint seems to work well with TypeScript, but my project compilation is successful despite encountering errors. It's puzzling why the comp ...

Quick + Vue Router - Lazy Loading Modules

For my personal project, I am using Vite alongside Vue 3 and have integrated vue-router@4 for managing routes. Since all of my modules share the same set of routes, I created a helper function: import { RouteRecordRaw } from 'vue-router' import p ...

Can we improve the coding of this as it seems inefficient and uses up too much room?

Do you think there is a more efficient way to write this code? It seems quite impractical and takes up a lot of space. Essentially, it's about the random chance of obtaining a rarity, like acquiring an Uncommon sword. if (Math.random() * 100 < 100 ...

How can I test Angular Router using Jest?

I'm currently experimenting with testing the functionality of a collapsed element in a sidebar when a user navigates to a specific page. I'm encountering some challenges in trying to simulate the behavior of the Angular Router in my Jest tests. ...

rxjs iterates through an array executing each item in sequential order

Is there a way to make observables wait until the previous one has completed when they are created from an array? Any help is appreciated! export class AppComponent{ arr: number[] = [5, 4, 1, 2, 3]; fetchWithObs() { from(this.arr) ...

What is the best way to bring a module into an Angular project?

I have a project in Angular with an additional module created as an npm package. The structure of the module is as follows: --otherModule --other-module.module.ts --index.ts --package.json index.ts: export { OtherModule } from './other-module ...

What is the best way to dynamically implement text ellipsis using CSS in conjunction with Angular 7?

i need to display a list of cards in a component, each card has a description coming from the server. In my component.html, I am using a ngFor like this: <div [style.background-image]="'url('+row.companyId?.coverUrl+')'" class="img- ...

Exploring Vue.js lifecycle events and when to begin loading store properties (Vue.observable)

Currently, I am utilizing Vue.observable() for state management and it is crucial for two store properties to be fully loaded before most views are rendered by vue-router. I have attempted implementing the loading logic in various lifecycle events such as ...

Can you explain the purpose of FunctionConstructor in typeScript?

As I delved into the Typescript Ecmascript source code, I stumbled upon this intriguing snippet: interface FunctionConstructor { /** * Creates a new function. * @param args A list of arguments the function accepts. */ new(...args: st ...

The TSX file is encountering difficulty rendering an imported React Component

Upon attempting to import the Day component into the Week component (both .tsx files), an error is thrown: Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. ...

What is the best way to assign a value to an ngrx reducer/action in order to update the state?

As a newcomer to Angular ngrx, I am in the process of integrating it into my 'standard beginner-project' by replacing all @Input()s and @Output()s. While incrementing and decrementing the state is straightforward, I am faced with the challenge of ...

What is the reason behind having to refresh the page or switch to another tab for the field to display?

Currently, I am in the final stages of completing my update form. However, I am facing an issue with the conditional field. The select field should display a conditional field based on the selected value. The problem I'm encountering is that I need to ...

Get the most recent two files from a set

I am currently facing a challenge in retrieving the first 2 documents from a collection in google cloud firestore. My current approach involves using the timestamp of the latest document and then calculating the time range to fetch the desired documents. l ...

Is it possible to create dynamic meta tags in Angular that will appear in a Twitter-style card preview?

My project involves building a dynamic website using a Java app that serves up a REST-ish JSON API along with an Angular9 front end. A key requirement is the ability to share specific URLs from the app on platforms like Twitter and Slack, which support Twi ...

Navigating through Observables in Angular Applications

In my Angular application, I am utilizing the RxJs library to retrieve data from a backend API server. The method for this call is shown below: allPowerPlants(onlyActive: boolean = false, page: number = 1): PowerPlant[] { const self = this; const ...

Choosing the default drop-down option in Angular based on a falsy value

Within this template, the "Select Military Status" choice will be selected if the underlying model.militaryStatus property is null. <select [(ngModel)]="model.militaryStatus"> <option [ngValue]="null">Select Military Status</option> ...

What is the best way to incorporate multiple pages and export them in an angular2 project?

Having some issues with my code. Can anyone lend a hand? import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: `page1.html` }) @Component({ selector: 'my-app2', templateUrl: `page2.html` ...