Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I flatten the response using RxJs

Right now for the operation mentioned in title I have the following code

from(["url_1", "url_2"])
  .pipe(
    concatMap(url=> this.vocabularyService.getSimilarProducts(url)
      .pipe(concatMap(x => x.items))
    ),
    toArray()
  )
  .subscribe(res => console.log(res));

What it does that for each URL in the array of URLs it makes an API call that returns something like this

class Response {
   items: Object[] // this is a specific type, but let's omit this for simplification
}

After receiving the response I again need to do a concatMap() to retrieve each of the items array item and eventualy I do the toArray() to somewhat flatten each item into single array and log it into console.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Does RxJs have any specific operator to do this kind of thing or is it possible to avoid my stacking of concatMap() operators?

>Solution :

You can use reduce to flatten the array like so.

import { Component } from "@angular/core";
import { from, of } from "rxjs";
import { concatMap, reduce } from "rxjs/operators";


@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Angular';
  subscripber = {
    next: (i) => console.log(i),
    complete: () => console.log('end'),
  };

  ngOnInit() {
    from(['url_1', 'url_2'])
      .pipe(
        concatMap((url) =>
          of({
            items: [1, 2, 3],
          })
        ),
        reduce((acc, one) => {
          acc.push(...one.items);
          return acc;
        }, [])
        // smaller version
        // reduce((acc, one) => [...acc, ...one.items], [])
      )
      .subscribe((res) => console.log(res));
    // Open the console in the bottom right to see results.
  }
}

stackblitz

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading