Reputation: 161
I have a relatively complex nested observable that switches to other observables and needs the info returned from each previous observable. Something like:
of(1).pipe(
switchMap(res =>
of(2).pipe(
switchMap(res2 =>
of(3).pipe(
switchMap(res3 => {
console.log(res)
console.log(res2)
console.log(res3)
return of()
}
)
)
)
)
)
)
Is there a way to accomplish this without the nested callbacks of the switchmaps? The main issue is having to remember the value emitted from each nested observable.
Upvotes: 0
Views: 63
Reputation: 691765
Sure. All you need to do is to reemit the previous values:
of(1).pipe(
switchMap(res => of({ res1: res, res2: 2 })),
switchMap(res => of({ ...res, res3: 3 })
).subscribe(...)
or
of(1).pipe(
switchMap(res1 => of(2).pipe(map(res2 => ({ res1, res2 }))),
switchMap(res => of(3).pipe(map(res3 => ({ ...res, res3 })))
).subscribe(...)
Upvotes: 3
Reputation: 11934
I think this can do the job:
of(1).pipe(
switchMap(res => forkJoin(of(res), of(2))), // Returns [1, 2]
switchMap(res => forkJoin(...res.map(v => of(v)), of(3))), // forkJoin(of(1), of(2), of(3))
switchMap(res => forkJoin(...res.map(v => of(v)), of(4))),
).subscribe(console.log) // 1, 2, 3, 4]
Upvotes: 0