Creating and handling Observable of Observables in RxJS: Best practices

Within my Angular application, there are multiple services that have dependencies on each other. To manage this, I have created a dependency map as shown in the example below:

let accountInitialization$: Observable<void>;
let productInitialization$: Observable<void>;

const dependenciesMap = {
  accountService: [],
  productService: [
    accountInitialization$ // There could be one or more dependencies
  ]
}

accountInitialization$ = this.getDependencies(dependenciesMap.accountService)
  .pipe(
    mergeMap(_ => {
      return this.accountService.initialize();
    })
  );

productInitialization$ = this.getDependencies(dependenciesMap.productService)
  .pipe(
    mergeMap(_ => {
      return this.productService.initialize();
    })
  );

accountInitialization$.subscribe(() => {
  this.progressUpdate.next(StartUpProgressUpdate.AccountsInitialized);
});

productInitialization$.subscribe(() => {
  this.progressUpdate.next(StartUpProgressUpdate.ProductsInitialized);
});

forkJoin([accountInitialization$, productInitialization$]).subscribe(
  () => {
    // perform some actions after initialization
  },
  error => {
    console.log(error); // This is where errors are handled
  }
);

The Product Service relies on the initialization of the Account Service. The getDependencies function has the following structure:

private getDependencies(dependencies: Observable<void>[]) {
if (dependencies.length) {
  return forkJoin(dependencies);
}
return EMPTY;

}

In this scenario, the goal is to ensure that the Account Service initializes before the Product Service. However, an error message is being encountered:

ERROR TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.

It appears that the .initialize() functions are not being invoked...

If you have any insights on how to resolve this issue, your assistance would be greatly appreciated. Thank you.

Answer №1

Instead of using forkJoin, you should consider utilizing switchMap. The structure could be similar to the following example:

import { switchMap } from 'rxjs/operators';
...
productInitialization$ = this.accountInitialization$.pipe(
  switchMap(accountInitializtion => {
    console.log('account initialization finished with: ', accountInitialization);
    // switch to this observable once complete
    return this.productService.initialize();
  });
)

Your specific case may require a different approach, so explore options like concatMap, switchMap, mergeMap for transitioning between Observable streams.

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

Retrieving input values using alert-controller in Typescript for Ionic framework and Angular

I am working with the Ionic (angular) framework and I need to extract information from the alert-controller inputs in order to utilize them within a function. Is there a method for accomplishing this? async presentAlertPrompt(resp) { const alert = await ...

Develop an Angular 6 application that utilizes an observable to monitor changes in a variable

I am working with Angular 6 and I need to monitor a variable for any changes and then stop or unsubscribe when the variable has a value. My initial thought was to use an Observable: myValue; // The variable that needs to be monitored myObservable = Obse ...

Observable<void> fails to trigger the subscriber

I am currently facing a challenge with implementing a unit test for an Observable in order to signal the completion of a process. While there is no asynchronous code in the logout function yet, I plan to include it once the full logic is implemented. The m ...

The fillFormValues function is not functioning properly within the mat-select element

I need help filling a form value by id. This function successfully retrieves the value: fillFormValues(expenseCategory: ExpenseCategory): void { console.log('response', expenseCategory.parent_category) this.aa= expenseCategory.parent_c ...

Using an angular 4 static method with a non-static object as an argument

Currently, I am working on an Angular 4 application and facing an issue while trying to pass the current language to the toLocaleString() method. The mathRound method is static, which makes it difficult to understand this.translation.currentLang. How can ...

Injecting Dependencies into an Angular 6 Service

Within my typescript file, I have a collection stored in an array. component.ts list: any[]; constructor( private listProcessor: ListProcessor ) {} ngOnInit() { this.listProcessor.getListItems() .subscribe( res => { th ...

What is the best way to convert the reader.result into a string?

Whenever I attempt to upload an image on Angular, I encounter an error with reader.result in the TypeScript file below. How can I resolve this issue? I even included console.log(image) in the onImagePicked function but it doesn't display anything in ...

I'm experiencing issues with my Ionic application Dockerize not properly functioning in the browser

I'm currently working on an Ionic study app in order to familiarize myself with Docker. I have completed all the necessary steps to create the image: 1. First, I created the Dockerfile with the following scripts: FROM node:18.10.0-alpine3.15 WORKDIR ...

Is there a way to access the final child element within a mat-accordion component using Material-UI and Angular 8?

I have a mat-accordion element with multiple expansion panels that are generated dynamically. How can I programmatically select and expand the last mat-expansion-panel element? <mat-accordion> <mat-expansion-panel> text 0 </mat-ex ...

The storage does not reflect updates when using redux-persist with next-redux-wrapper in a Typescript project

I'm currently working on integrating redux-persist with next.js using next-redux-wrapper. However, I'm facing an issue where the storage is not updating and the state is lost during page refresh. Below is my store.ts file: import { createStore, ...

Intermittent issue with Angular 2 encountered while following the Hero Editor tutorial on angular.io

I am encountering an occasional error in the console while following the angular.io tutorial using Mozilla Firefox. The error does not seem to impact the functionality or rendering of my application, and it only happens sporadically. If you could provide ...

Setting up Datatable in Angular 2+ without relying on jQuery

I need assistance with initializing a datatable for a table that has a unique id. Can you provide guidance on the syntax to achieve this? Here is an example of my table structure: <table id="myDataTable"> <thead> <tr> ...

Using typescript with create-react-app - organizing types in a separate file

I'm currently developing a project using Create React App with TypeScript (create-react-app myapp --typescript) In my App.tsx file, I have written some TypeScript code that I want to move to an external file. I have tried creating App.d.ts, index.d.t ...

The issue of Rxjs Subject in Angular2 running twice persists even after unsubscribing

Currently, I am developing a desktop application using angular2 and electron with a download feature integrated within it. The code for my DownloadService looks like this: import {Injectable} from '@angular/core'; import {Subject} from "rxjs"; ...

Error encountered: Parsing error in Typescript eslint - The use of the keyword 'import' is restricted

My CDK application is written in typescript. Running npm run eslint locally shows no errors. However, when the same command is executed in a GitLab pipeline, I encounter the following error: 1:1 error Parsing error: The keyword 'import' is r ...

Vue3 project encountering issues with Typescript integration

When I created a new application using Vue CLI (Vue3, Babel, Typescript), I encountered an issue where the 'config' object on the main app object returned from the createApp function was not accessible. In VS Code, I could see the Typescript &ap ...

Error: Could not locate module: 'path' in ' ode_modulessource-map-support' - npm

During the migration process from Angular 5 to Angular 7, I encountered a couple of errors such as map and forkJoin being deprecated. Thankfully, those issues were resolved. However, there is still one lingering error that crops up when running ng serve. ...

When utilizing the useRef hook in Material-UI, an error may arise stating: "The property 'value' is not found on the type 'never'."

Currently, I am utilizing material UI to construct a login and registration page. In the process, I am leveraging the useRef hook to retrieve a reference instance for a TextFiled, and using xxxRef.current.value to access the input value. Despite being abl ...

Encountering a warning during the installation of Angular CLI

As a newcomer to this platform, I recently installed Node.js. However, when attempting to execute the command npm install -g @angular/cli, an error was encountered: **npm WARN deprecated [email protected]: Legacy versions of mkdirp are no longer supported ...

Do I have to utilize npm packages?

As a newcomer to Node.js, I'm diving into the world of node features while working on an Angular 2 project. One thing I've noticed is that every plugin seems to be imported from the node_modules folder. This has me wondering - is it absolutely n ...