Best practices for patiently waiting for arranged observables and linking the outcome

I have a sequence of observables that need to be executed in order, but I want to keep them cold (without subscribing) so that further chaining is possible.

const tasks = [observable1, observable2, observable3];

If I return concat(...tasks) and then try to chain from it

tasks$.pipe(switchMap(() => ...))
, the switchMap will run for each observable inside concat - 3 times.

I am searching for a solution similar to forkJoin where

forkJoin(...tasks).pipe(switchMap(() => ...))
in which the switchMap will only execute once. However, using forkJoin alone won't work since the order should also be maintained.

The options I've explored so far are:

  1. Return forkJoin(concat(...tasks)). This technically works because forkJoin waits for concat to complete, but it feels inefficient since forkJoin is designed to handle multiple observables, not just one.
  2. Return concat(...tasks).pipe(toArray()). This might be better than forkJoin but still doesn't feel like the most efficient solution. Another option is takeLast() which serves a similar purpose but implies an emphasis on the last value rather than completion. Something like finalize() would be ideal, but with the ability to emit in order to block the stream when needed.

(Check out Stackblitz examples here)

Is there a more suitable operator for waiting for concat to finish or a better alternative to concat altogether that maintains the order of execution and allows for seamless chaining like forkJoin? It seems like there should be a basic operator that simply waits for a source observable to complete and then emits the result, considering the availability of operators like forkJoin for handling multiple observables and maintaining their order.

Answer №1

It seems like the solutions you have developed so far are on the right track. However, I suggest a different approach that utilizes the concat function along with the reduce operator to potentially enhance clarity:

concat(...work).pipe(
    reduce(() => undefined)
);
  • The concat function ensures observables are executed sequentially.
  • The reduce operator emits once when its source emits
    • The () => undefined signifies that the value is not of importance in this context.

Check out the demo on StackBlitz.

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

I designed a dropdown menu with a searchable <mat-select> feature, where selecting an item is automatic when a space bar is pressed in the search box

Description : I have implemented a dropdown list using element that contains a list of items along with a search field. This allows users to easily search for specific items in the list instead of manually scrolling through a long dropdown menu. They can ...

What is the best way to present sorted items on a user interface?

I have a unique Med interface containing properties like drugClass, dosage, and name. Using this interface, I created an array of drugs with different attributes. How can I filter this array by drugClass and then display the filtered data on a web page? ...

Unable to retrieve the value from the nested formGroup

I am currently in the process of setting up nested formGroup fields using HTML code. <form [formGroup]="userProfileForm" (ngSubmit)="bookUser()" class="form"> <!-- userName --> <div class="form-group"> <label for="user ...

Exploring the differences between Office Fabric UI's I[component]StyleProp and the I[component]Styles interface

The Office Fabric UI documentation provides two interfaces for each component, such as https://developer.microsoft.com/en-us/fabric#/components/nav includes INavStyleProps interface and INavStyles interface A component that implements INavStyleProps ...

In the function ngOnChange, the SimpleChange currentValue is supposed to be defined, but for some reason, the

Within the TypeScript code, a name variable is assigned input from another component. @Input() name : any ; In the ngOnChange function, I retrieve and print the SimpleChange object in the following manner. ngOnChanges(changes: SimpleChange){ console.l ...

Alias route for `src` in Ionic 3

I have set up a custom webpack configuration for Ionic 3 in order to use src as a path alias (meaning I can import from src/module/file): resolve: { alias: { 'src': path.resolve('./src') } } However, after updating to Ionic ap ...

Binding an event to an Angular 2 component directly within its selector code

Looking at my Angular 2 component: import { Component, ElementRef, Renderer } from '@angular/core';; @Component({ selector: 'my-button', templateUrl: 'button.html' }) export class ButtonComponent { private text: string ...

Changes made in the Firestore console do not automatically activate the snapshotChanges subscription

I'm facing an issue with subscribing to a document in Firestore using AngularFire. Even after making changes to the document through the Firestore console, I don't see any updates reflected in the pulled data, even after refreshing locally. The D ...

Utilizing an AwsCustomResource in AWS CDK to access JSON values from a parameter store

I found a solution on Stack Overflow to access configurations stored in an AWS parameter. The implementation involves using the code snippet below: export class SSMParameterReader extends AwsCustomResource { constructor(scope: Construct, name: string, pr ...

Tips for displaying dynamic HTML content in Angular

Is there a way to dynamically display HTML content within {{ name }}? let firstName = "Faisal"; let data1 = "<h1>{{firstName}}</h1>"; let lastName = "Khan"; let data2 = "<h1>{{lastName}}</h1>"; How can I achieve the desired outpu ...

Angular's detectChanges method seems to be failing when called on a child component

I've encountered an issue with change detection in my Angular application. For some reason, the change detection stops at the first child in the hierarchy. When I manually invoke change detection one level deeper (in `sch-job-detail`), then the values ...

What is the reason behind create-next-app generating .tsx files instead of .js files?

Whenever I include with-tailwindcss at the end of the command line, it appears to cause an issue. Is there any solution for this? npx create-next-app -e with-tailwindcss project_name ...

Angular Material calendar tool customization for designated input

Is it possible to individually control the format of input for a datepicker without affecting the format for the entire module? <input matInput [matDatepicker]="dp" [formControl]="date" [format]="'DD/MM/YYYY'"> <-- Can this be done? < ...

What method does Angular use to distinguish between familiar elements and unfamiliar ones?

<bar>- it is a tag with a random name, not officially recognized, so it makes sense that it is considered invalid <div> is valid because it is a standard HTML element - does Angular have a documented list of standard elements? Where can I fin ...

What could be causing my Bootstrap accordion to not expand or collapse within my Angular application?

Struggling with my Accordion Angular component that utilizes Bootstrap - the collapsing and expanding feature isn't functioning properly. I've simply copied the bootstrap code into my accordion.component.html. <div class="accordion accord ...

Tips for setting up communication between UI and backend applications using Nginx reverse proxy in a Docker environment

We have an Angular UI application and a Java Spring Boot backend application. Our goal is to deploy them in Docker containers and establish seamless communication between the front-end and back-end without hard-coding URLs or other specifics. Everything ne ...

Tips for Crafting a Mutation Response Evaluation

When I execute a graphql mutation, the code looks like this: interface SignInReponse { loginEmail : { accessToken: string; } } const [login] = useMutation<SignInReponse>(LOGIN); This is how the mutation appears in the schema: loginEmail( ...

Manually close the AntD Menu without using any shortcuts

I'm facing a unique situation with my table implemented using antd. Each row has a dropdown menu that opens a modal upon clicking. To ensure the dropdown menu doesn't trigger the row click event, I used stopPropagation on the menu item click. Eve ...

Creating dynamic components from JSON elements does not trigger a rerender of components within an array

Imagine having a simplified input structure like this: [ { type: "text", text: "how are you {name}" }, { type: "input", input: "name" }, { type: "text", text: "good to ...

During the process of running mocha tests, an error is encountered stating that a "reflect-metadata shim is necessary when utilizing class decorators."

Recently, I wrote a Mocha test case using Chai in Typescript and followed the steps outlined in this article here to install all the necessary dependencies. However, when trying to run the test cases with "npm test", I encountered the following error mess ...