Search code examples
javascriptrxjs5reactive-extensions-js

RxJS - concatenate mapped elements onto a stream


Is there is an operator which allows me to map over elements of a stream but instead of transforming them, concatenating them?

I have a stream

A => B => C

items$.concatMap(x => f(x)) would lead to

"f(A)" => "f(B)" => "f(C)"

while concat does not receive an element as param so that won't work either

I want to achieve:

"A" => "B" => "C" => "f(A)" => f(B) => "f(C)"

This will do it but I have to annoyingly break up and store my stream (I guess it's fine for a small example but on a longer pipeline it is more troublesome).

item$ = Observable.of("A","B","C");

item$.concat(item$.map(x => f(x)));

Solution

  • I finally discovered the right operator for this (at the time of writing I couldn't find it in the RxJS 5 docs), but it is called let and gives you the whole current observable as an argument.

    item$.let(obs$ => obs$.concat(obs$.map(f));
    

    Which is not really impressive if its the first operation, it's really useful but you could have more stuff in front and want to avoid having to stop and store the stream in a local variable:

    item$.debounce(1000)
         .map(z => f(z.id))
         .moreOperators(...)
         .let(obs$ => obs$.concat(obs$.map(f));