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)
          .pipe(
            map((value) => {
              return this.getData(value);
            })
          )
          .subscribe((data) => {
            console.log(data);
            /**
             * The expected output should be
             * 5 completed
             * 4 completed
             * 1 completed
             * 2 completed
             * 3 completed
             */
          });
      }
    
      getData(p: number) {
        return new Observable<string>((s) => {
          setTimeout(() => {
            s.next(`${p} completed`);
            s.complete();
          }, p * 1000);
        });
      }
}

Answer №1

Consider using concatMap.

export class AppComponent{
    data: number[] = [5, 4, 1, 2, 3];    
    fetchData() {
        from(this.data)
          .pipe(
            concatMap(this.obtainData)
          )
          .subscribe(console.log);
      }
    
      obtainData(num: number) {
        return new Observable<string>((observer) => {
          setTimeout(() => {
            observer.next(`${num} processed`);
            observer.complete();
          }, num * 1000);
        });
      }
}

Check it out on Stackblitz: https://stackblitz.com/edit/typescript-axx8gf?file=index.ts

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

Manipulating toggle buttons using CSS and jQuery

Check out this jsfiddle to see my attempt at creating a toggle switch in the form of a mute button. The toggle button shows the current setting: mute or unmute When hovered over, it displays the alternative setting However, I am encountering an issue wh ...

Guide to automatically blur the input field and toggle it upon clicking the checkbox using Angular

<input (click)="check()" class="checkbox" type="checkbox"> <input [(ngModel)]="second_month" value="2019-09" type="month" [class.blurred]="isBlurred">> I need the second input(type=month) field to be initially blurred, and only unblur ...

Developing a React-based UI library that combines both client-side and server-side components: A step-by-step

I'm working on developing a library that will export both server components and client components. The goal is to have it compatible with the Next.js app router, but I've run into a problem. It seems like when I build the library, the client comp ...

Steps for implementing a conditional statement to handle an empty string in HTML

I need to figure out how to display a different message if my string is empty. Can anyone help me with this? <div class="padding" id="dealBorder"> <pre id="informationDealText"><pan class="inner-pre" style="font-size: 24px; color: whi ...

The type 'Event' argument cannot be assigned to the 'InfiniteScrollCustomEvent' parameter

I'm facing an issue with Ionic Angular. Here is my movies.page.html: <ion-header> <ion-toolbar color="primary"> <ion-title>Trending Movies</ion-title> </ion-toolbar> </ion-header> <ion-content ...

Issue with CSS: 200vw not scaling correctly for mobile devices

I'm attempting to create a horizontal slide effect between two div elements, so here is the HTML code: <div id="container"> <div class="viewport-1"> <div class="inner-div"> <h1>Viewport background 1</h1></ ...

What is the best way to save inputted names as properties of an object and assign the corresponding input values as the values of those properties?

I am searching for a way to dynamically build an object where each property corresponds to the name of an input field and the value of that property is the input's value. Here is the HTML structure: <form> <fieldset> ...

Having trouble with clearInterval in React TypeScript?

I have been encountering issues with the clearInterval function in TypeScript for React. I am not sure why the interval is not being cleared. To address this problem, I defined a variable let interval_counter;, and used it as follows: interval_counter = ...

What is the best way to handle various sections with changing structures within a complex form using react-hook-form?

I am working on a complex form that has sections A, B, and C, each of which can be in shape A1 or A2, B1 or B2, C1, or C2. Users are required to fill out settings based on whether the section is set to "advanced" or "basic". I want users to submit the enti ...

What's the process for changing this arrow function into a regular function?

Hello from a child component in Vue.js. I am facing an issue while trying to pass data from the parent via sensorData. The problem lies in the fact that the arrow function used for data below is causing the binding not to occur as expected. Can anyone gu ...

Looking to display all items once the page has finished loading

I am experiencing a minor issue. Every time I access my store page where all products are listed, I have to click on the size filter to load the products. This is not ideal as I want all products to be displayed automatically when the page loads. What modi ...

Experiencing issues with obtaining req.params.id undefined while initiating a put request

Encountering an issue while making a PUT request using Postman, as an error occurs in the VSCode terminal with the message: let product = await Product.findById(req.params.id); ^ TypeError: Cannot read property 'id' of undefined. The request ...

Generating a composer method in TypeScript (Flow $Composer)

While flow supports $Compose functions, the equivalent mechanism seems to be missing in TypeScript. The closest thing I could find in TypeScript is something like https://github.com/reactjs/redux/blob/master/index.d.ts#L416-L460. Is there a native equivale ...

Has anyone figured out the issue with Uplodify? It suddenly ceased to function

For some time now, I've been using uplodify without any issues. Unfortunately, as of yesterday, it suddenly stopped working. I'm at a loss as to what might have caused this sudden change. Could someone please offer me some assistance? I've ...

The issue in Vue JS arises when trying to access JSON key values from an object array using v-for

I am currently working on parsing a list of objects found within a JSON payload into a table utilizing Vue.js. My goal is to extract the keys from the initial object in the array and use them as headings for the table. While the code I have in place succe ...

jQuery unable to find designated elements in uploaded templates

I have a specific route linked to a specific controller and view: app.config(['$routeProvider', function ($routeProvider) { $routeProvider .when('/create', { templateUrl: 'partials/form/form.html', controlle ...

Exploring Angular: Embracing the Power of Query String Parameters

I've been struggling with subscribing to query string parameters in Angular 2+. Despite looking at various examples, I can't seem to make it work. For instance, on this Stack Overflow thread, the question is about obtaining query parameters from ...

Leverage the specific child's package modules during the execution of the bundle

Project Set Up I have divided my project into 3 npm packages: root, client, and server. Each package contains the specific dependencies it requires; for example, root has build tools, client has react, and server has express. While I understand that this ...

What is the method to acquire the firestore reference type in TypeScript?

Here is the code I am working with: import { DocumentReference } from '@firebase/firestore-types' export type Recipe = { author: string title: string ingredients: { quantity: number ingredient: DocumentReference["path"] ...

employing strings in passing functions as arguments

The script below, taken from a tutorial by Adam Khoury, is designed to create a timer that displays a message once it reaches completion. While I grasp the overall functionality of the code, I'm puzzled by the use of strings in certain parts: 1) Why ...