Search code examples
typescriptrxjsrxjs6

I have an Observable object stream and am trying return a Observable<string> stream from an array member


I need to filter a list of objects and create an distinct observable stream from a string[] member. Typescript 2.9.2

interface Product2 {
  id: number;
  categories: string[];
}

const products: Product2[] = [
   {id: 1, categories: ['abc', 'def']},
   {id: 2, categories: ['def', 'xyz']}
];
const products$: Observable<Product2> = from(products);

const allCategories$: Observable<string|void> = products$
  .pipe(
      map((val: Product2) => { from(val.categories).subscribe(); } ),
      distinct()
  );

console.log('logging categories');
allCategories$.subscribe(val => console.log(val));

Expected 'abc', 'def', 'xyz' got undefined.


Solution

  • map operator requires the inner function to return a value. You're returning undefined because you have no return statement there.

    Anyway, you can use mergeMap to unwrap the array of categories into separate emissions then then distinct() will do its job:

    const allCategories$: Observable<string|void> = products$
      .pipe(
        mergeMap((val: Product2) => val.categories),
        distinct()
      );