Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use map and switchMap together

I have an observable with object containing usual field and other observable. I want to get sequence containing this field and the value of corresponding observable firing together with inner observable.

For example:

var smth$ = interval(1000).pipe(
  take(3),
  map(i => ({
    id: String.fromCharCode('A'.charCodeAt(0) + i),
    value$: interval(300).pipe(
      take(10),
      map(j => i*10 + j)
    )
  }))
)

I can easily get sequence of id field via map:

smth$.pipe(
  map(x => x.id)
)

ids by <code>map</code>

Also I can get sequence of values via switchMap:

smth$.pipe(
  switchMap(x => x.value$)
)

values by <code>switchMap</code>

But how can I get a sequence of pairs with both id and value?

desired sequence

Runable example: https://rxviz.com/v/R85xKw6J

like image 211
Qwertiy Avatar asked Sep 19 '25 19:09

Qwertiy


2 Answers

Flat solution: https://rxviz.com/v/j8ArKWEo

smth$.pipe(
  switchMap(x => x.value$, (x, d) => x.id + d)
)
like image 112
maxime1992 Avatar answered Sep 21 '25 08:09

maxime1992


You can try

smth$.pipe(
    switchMap(x => x.value$.pipe(
        map(d => x.id + d)
    ))
)
like image 40
Picci Avatar answered Sep 21 '25 08:09

Picci