简体   繁体   中英

Convert array of observables of observables to array of observables rxjs

To simplify the problem i have used numbers and strings here. The code:

const numbers$:Observable<number[]> = of([1,2,3]);
const strings: string[] = ["a","b"];

function getStrings(): Observable<string>[]{
   return numbers$.pipe( 
     map((numbers: number[]) => {
       const strings$: Observable<string>[] =  strings.map(s => of(s));
       return strings$;
     }),
  )
}

getStrings().subscribe(x => console.log(x))

The error i am getting is: Type 'Observable<Observable<string>[]>' is missing the following properties from type 'Observable<string>[] How can i get Observable<string>[] from getStrings function? I have tried to use flatMap, switchMap but unable to get the perfect combination.

Stackblitz

You'll need to use mergeMap() and forkJoin() :

function getStrings(): Observable<string[]>{
   return numbers$.pipe( 
     mergeMap((numbers: number[]) => {
       const strings$: Observable<string>[] =  strings.map(s => of(s));
       return forkJoin(strings$);
     }),
  )
}

getStrings().subscribe(x => console.log(x))

https://stackblitz.com/edit/rxjs-dzvsbh?file=index.ts

So as I understand you want to "zip" two lists together, via observable ?

I can offer you this one


    const numbers$: Observable<number[]> = of([1, 2, 3]);
    const strings$: Observable<string[]> = of(['a', 'b']);

    const combined$: Observable<any> = zip(numbers$, strings$)
      .pipe(
        map(([numbers, strings]) =>
          numbers.length > strings.length ?
            numbers.map((value, index) => [value, strings[index]]) :
            strings.map((value, index) => [numbers[index], value]))
      );

    combined$.subscribe(value => console.log(value));

This will log: [ [ 1, "a" ], [ 2, "b" ], [ 3, null ] ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM