6

I have an Observable<Recipe[]> that I want to reduce to an array of a different class ChartData[] to use as a data source for a highcharts graph (column and piechart).

I am trying to use the RxJS pipe operator on the Observable<Recipe[]> to call the reduce operator on my data but I cannot get it to work? The reduce operator does not iterate over them items in my Observable<Recipe[]> Below is my attempt:

this.foodService.getAllReceipes()
  .pipe(
    reduce((array: ChartData[], value: Recipe[], i: number) => {
        const author = this.createOrFindAuthor(array, value[i]);
        author.y += 1;

        return array;
      }, new Array<ChartData>())
  )
  .subscribe(data => this.chartData$ = of(data.sort((a, b) => b.y - a.y)));
}

getAllRecipes() returns the Observable<Recipe[]>

this.chartData$ is Observable<ChartData[]>

I am trying to reduce this to ChartData[]. I have been able to do this in the subscribe operator and the graphs display the expected data but I thought I should be able to do it as a pipeable operator? Here is the reduce being done as part of the subscribe:

this.foodService.getAllReceipes()
  .subscribe((data) => {
    const list = data.reduce((arr: ChartData[], v: Recipe) => {
      const author = this.createOrFindAuthor(arr, v);
      author.y += 1;

      return arr;
    }, new Array<ChartData>());

    this.chartData$ = of(list.sort((a, b) => b.y - a.y));
  });

I have tried using the subscribe code within the pipeable reduce but I get compile errors saying that the method expects Recipe[] for the value. But if I use the array then I only get the first element from the Observable (or am I just getting the Observable and need to do something with that?)

Is this possible or is my thought process wrong about how the pipeable operator should work on the Observable?

For reference here are the models and the createOrFindAuthor function:

export class Recipe {

    public Title: string;
    public Author: string;
    public Source: string;
    public Page: number;
    public Link?: string;
}

export class ChartData {
    name: string;
    y: number;
}

private createOrFindAuthor(array: ChartData[], recipe: Recipe): ChartData {
  const name = (recipe.Author.length > 0 ? recipe.Author : 'UNKNOWN');

  let found = array.find(i => i.name === name);

  if (!found) {
    const newData = new ChartData();
    newData.name = name;
    newData.y = 0;
    array.push(newData);

    found = newData;
  }

  return found;
}

3 Answers 3

5

So Chau Tran put me on the right lines. Apparently I needed to switchMap the Observable to a Recipe[] and the reduce operator was then happy to accept a Recipe as the value. Solution as follows:

this.foodService.getAllReceipes()
  .pipe(
    switchMap(data => data as Recipe[]),            <<== ADDED THIS

    reduce((array: ChartData[], value: Recipe) => {
        const author = this.createOrFindAuthor(array, value);
        author.y += 1;

        return array;
      }, new Array<ChartData>()),

      switchMap(data => this.chartData$ = of(data.sort((a, b) => b.y - a.y)))
  )
  .subscribe();
2

After reduce, try:

switchMap(data => {
    this.chartData$ = of(data.sort((a, b) => b.y - a.y));
    return this.chartData$;
})
.subscribe()
3
  • Although that improves my code it doesn't solve the problem of getting the reduce operator to iterate over all the items in the Observable.
    – Simply Ged
    May 3, 2018 at 13:10
  • You put me on the right lines, just needed an additional switchMap :-)
    – Simply Ged
    May 3, 2018 at 13:18
  • Yeah my bad, for some reason I thought you'd get the Recipe[] in reduce already.
    – Chau Tran
    May 3, 2018 at 14:14
0

I created this stackblitz example to demo usage of reduce(). The project contains other stuff but what you need is in demoReduce.ts:

import { Observable, of } from 'rxjs'
import { reduce, tap } from 'rxjs/operators'

type Book = {
  title: string
  noPages: number
}

type Library = {
  totalPages: number
  books: Book[]
}

export const demoReduce = () => {
  const books$: Observable<Book> = of(
    { title: 'book 1', noPages: 10 },
    { title: 'book 2', noPages: 20 },
    { title: 'book 3', noPages: 30 },
  )

  return books$.pipe(
    // --- reduce a stream of "Book" into a "Library"
    reduce<Book, Library>((previous, book) => {
      // --- add book to "Library" and increment totalPages in "Library"
      return {
        totalPages: previous.totalPages + book.noPages,
        books: [
          ...previous.books,
          book
        ]
      }
    }, { totalPages: 0, books: [] }),
    tap(val => console.log(val))
  )
}

To execute the observable, use the "Demo Reduce" button, and look at console.

It converts a stream of Books into a single Library object.

Note:

  • I am not sure why stackblitz shows error (squiggly red underline) in the online editor for reduce(). I did not get the error in IntelliJ/WebStorm. I suspect is a stackblitz bug.

Update:

Here's the same function that takes Observable<Book[]> as input (not tested):

export const demoReduceWithArray = () => {
  const books$: Observable<Book[]> = of([
    { title: 'book 1', noPages: 10 },
    { title: 'book 2', noPages: 20 },
    { title: 'book 3', noPages: 30 }
  ])

  return books$.pipe(
    // --- reduce a stream of "Book[]" into a "Library"
    reduce<Book[], Library>((previous, books) => {
      // --- add each book to "Library" and increment totalPages in "Library"
      books.map(book => {
        previous = {
          totalPages: previous.totalPages + book.noPages,
          books: [
            ...previous.books,
            book
          ]
        }
      })
      return previous
    }, { totalPages: 0, books: [] }),
    tap(val => console.log(val))
  )
}
1
  • I just realized you need "Observable<Recipe[]>" instead of "Observable<Recipe>" as input. Sorry! Anyway, I hope the demo can serve as a guide to tweak from. :-)
    – kctang
    May 3, 2018 at 15:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.