Combining array elements into functions with RxJS observables

I am facing a scenario where I have an array of values that need to be processed sequentially using observables in RxJS.

Is there a more optimized way to achieve this instead of using nested subscriptions?

  let num = 0;

  let myObs = new Observable(observe => {
    observe.next(1);
  })
  let content=['x','y','z'];

  myObs.subscribe(data => {
    let i = 0;
    let self = this;
    let inlineFunction = function(){
      if (i < content.length){
        self.generate(num).subscribe(() => {
          i++;
          inlineFunction();
        });
      }else{
        observer.next(doc);
      }
    };
    inlineFunction();
  });

  generate(num:number) : Observable < any >{
    return num*num;
  }, 

Answer №1

If you're looking to continuously and repeatedly call an observable, you can utilize Observable.expand().

Let's say you have an array of content:

let content=['x','y','z'];

For each value in the content array, suppose you need to invoke a function called gen() which produces an Observable:

gen(num: number): Observable<any> {
    return Observable.of(num * num);
}

Here is how you can achieve this:

let myObs = Observable.of(1);
let num = 0;
let content = ['x','y','z'];

const gen = (num: number): Observable<any> => {
  return Observable.of(num * num);
}

myObs
.expand(()=>{
  return gen(num);
})
.skip(1)
.take(content.length)
.subscribe(x=>console.log(x));

Explanation:

  1. .expand() will continue to call the specified function (as the 1st argument) repetitively until instructed otherwise. In this case, it calls gen() which returns an observable.

  2. .skip(1) skips the initial emission where myObs has a value of 1.

  3. .take() stops the infinite .expand() loop after iterating through the length of the content array.

  4. .subscribe() is used to retrieve the results.

Comment: The output generated will be:

0
0
0
0

This is because the value of num is 0. It is assumed that gen() is a placeholder function which should be replaced with Observables returning actual meaningful data.

Check out the JSBin for a working example.

Answer №2

To begin, start by obtaining an observable of values using the from operator and then proceed to employ the reduce method:

Observable.from([...values])
    .reduce( this.reducingFn, 1 )

The reducingFunction is designed to take in two parameters: the initial value (which is the second argument in the reduce function) and the current value emitted by the outer stream (each value within the values array).

// Somewhere within your class
reducingFn(accumulatedValue, value){
    return accumulatedValue * value
}

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

Experiencing a problem in React JS when trying to render a component?

I encountered an error message while trying to render a component from an object. Type 'FC<Boxprops> | ExoticComponent<{ children?: ReactNode; }>' is not compatible with type 'FC<Boxprops>'. Type 'ExoticComponen ...

Exploring the return type of the `within` function in TypeScript Library

I have helpers set up for my React tests using the testing library: const getSomething = (name: string, container: Screen | any = screen) { return container.getByRole('someRole', { name: name }) } The container can be either the default screen ...

Angular with D3 - Semi-Circle Graph Color Order

Can someone assist me with setting chart colors? I am currently using d3.js in angular to create a half pie chart. I would like to divide it into 3 portions, each represented by a different color. The goal is to assign 3 specific colors to certain ranges. ...

I've tried using a ControlValueAccessor, but for some reason the value isn't getting passed to the form

Currently, I am experimenting with reactive forms in Angular, and I'm encountering difficulties with updating the form from custom components. As an example, take a look at the date-input component created using flatpickr in the linked Plunker demo. ...

Facing issue in Visual Studio 2015 with Angular 2 @component not able to resolve the signature of the class decorator

Trying to define a decorator on top of my class in Visual Studio 2015 is causing an error during the build process. The specific error message states: "Build: Unable to resolve signature of class decorator when called as an expression." import { Component ...

Tips for synchronizing the value of one field in a reactive form with changes in another field

I have a reactive form below where I'm using a form builder with groups. Fig: https://i.sstatic.net/gdc7p.png Here is the HTML code of the component <div class=""> <form [formGroup]="FeedBack" (ngSubmit)="on ...

TypeORM's one-to-many relationship alters the primary entity once the relationship has been established

When working on my side project, I decided to implement a friend request system using NestJS + TypeORM for the backend. However, I encountered a peculiar issue where every time I tried to associate a Friend entity with a specific user, the target field of ...

How can I take photos in bulk when I open the camera on Ionic 3?

Is there a way to capture multiple images at once using the camera? Currently, I am only able to capture one image when the user clicks. However, I would like to capture four images when the user clicks the success button. let options: CaptureImageOption ...

Distinguishing the switch function from the React switch operator (jsx, tsx)

We are in the process of converting our portfolio from JavaScript to TypeScript, utilizing NextJS as the frontend framework and Strapi as the backend. To enable dynamic content, we have implemented a dynamiczone field within the post model that is accesse ...

Universal Parameter Typing in Functions

I'm grappling with a concept that seems obvious to me, yet is disallowed by Typescript when all strict flags are enabled (presumably for valid reasons). Let me illustrate: We all understand the following: export interface Basic { value: "foo&q ...

Using Angular 2, you can pass an object as a parameter to a function

Is there a way to pass an object as a parameter in the DOM on this forum? Within my HTML code, I have the following: <div class="list-items"> <ul> <li *ngFor="let i of item"> <span (click)="onAdd({{newUser.us ...

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 ...

When trying to install my npm package from the registry, I keep encountering an issue despite being able to install it locally

I recently released my Node.js/typescript package on the npm registry, but I'm encountering issues when trying to install it from there. Oddly enough, local installation works perfectly fine. Here's the output from the local installation: $ npm ...

Utilize a list of Data Transfer Objects to populate a dynamic bar chart in recharts with

I received a BillingSummaryDTO object from a Rest API using Typescript: export interface BillingSummaryDTO { paid?: number, outstanding?: number, pastDue?: number, cancelled?: number, createdAt?: Moment | null, } export async function ...

Adjustable Material UI Switch that reflects the value, yet remains changeable

I am facing a challenge with integrating a Material UI switch (using Typescript) to showcase a status value (active/inactive) on my edit page, and making it toggleable to change the status. I have been able to either display the value through the switch OR ...

Typescript Angular2 filtering tutorial

In Angular 2 using TypeScript, the goal is to search for matching values from an array within an object array. The intention is to filter out any objects where the 'extraService' property contains any of the values from the 'array_values&apo ...

iterating through the checked values in Angular 4

I need assistance in writing a loop using TypeScript to send each checked employee as a parameter to the postCouncilAbsence function. Can anyone help? component.ts: onattendanceSave(form:NgForm){ this.index = this.attendanceForm.value console.log ...

How is it that in TypeScript, a potential numeric value in an interface can be transformed into an impossible numeric value in a class implementation?

Encountered a surprising behavior from the TypeScript compiler today. Unsure if it's a bug or intentional feature. If it is indeed intentional, I would like to understand the reasoning behind it. The issue arises when declaring an interface method wi ...

Is there a way to inform TypeScript that the process is defined rather than undefined?

When I execute the code line below: internalWhiteList = process.env.INTERNAL_IP_WHITELIST.split( ',' ) An error pops up indicating, Object is possibly undefined. The env variables are injected into process.env through the utilization of the mod ...

Value of type 'string' cannot be assigned to type '{ model: { nodes: []; links: []; }; }'

I am a beginner in TypeScript and I have added types to my project. However, I am encountering an error with one of the types related to the graph: Type 'string' is not assignable to type '{ model: { nodes: []; links: []; }; }'.ts(2322) ...