Vikas Kalapur
Vikas Kalapur

Reputation: 35

How to iterate the List inside the pipe in RXJS

I have a variable which is a list

this.formListModel = [studentData1,studentData2,studentData3]

Now i have to iterate each Student data in above list and need to pass in a method and that method will send these data to backend via API

So here is the small code

 1. this.odataNotificationService.cancelNotification(this.model)
 2.            .pipe(
 3.                tap(() => {
 4.                    someFunctionality..
 5.                    someFunctionality..
 6.                }),
 7.                flatMap(() => this.someFunctionWhichReturnsObservable()),
 8.                flatMap(() =>  this.someSecondFunctionWhichReturnsObservable()),
 9.                flatMap(() => this.formListModel.map(()=>{
                                      return this.thirdFunctionWhichReturnsObservable(form.identifier)
                                   }))

Now I have a problem in line 9 and 10

Here i have a list which is stored in a variable this.formListModel where i need to iterate data nd need to send in the Next function this.thirdFunctionWhichReturnsObservable(form)

I have used a map inside flatMap which will never work. So I am looking for a solution where I can iterate inside the pipe

Upvotes: 0

Views: 1008

Answers (2)

lorenzbayr
lorenzbayr

Reputation: 11

This solution emits an observable for each element inside this.formListModel using the from creational operator. Inside mergeMap the observable is subscribed to, and the result observable of this.thirdFunctionWhichReturnsObservable is returned. When the outer stream from(this.formListModel) completes the toArray() operator bundels all results from this.thirdFunctionWhichReturnsObservable and emits an array.

You might have to adjust this solution to your needs. I hope it helps. Replace line 9 with:

    switchMap(() => from(this.formListModel)),
    concatMap(identifier => this.thirdFunctionWhichReturnsObservable(form[identifier])),
    toArray()

I used mergeMap assuming that the order, the results of this.thirdFunctionWhichReturnsObservable are returned in matters. If it doesn't, then use mergeMap.

You can read about rxjs flattening operators here:

Upvotes: 0

AliF50
AliF50

Reputation: 18899

I would do something like this:

9.) flatMap(() => combineLatest(...this.formListModel.map(form => this.thirdFunctionWhichReturnsObservable(form.identifier))),

You may have to switch flatMap to a switchMap, I am not sure about this one. You can also use forkJoin instead of combineLatest. It is for you to experiment. If you need to send the requests in series, I am not sure in how to do that.

Upvotes: 2

Related Questions