Reputation: 101
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.
Upvotes: 0
Views: 50
Reputation: 96891
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
Upvotes: 1
Reputation: 2148
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 ] ]
Upvotes: 0