Supamiu
Supamiu

Reputation: 8731

MergeMap for each expand occurence

I want to create an Observable chain which will be able to add http data to each expand occurence before the next one and I can't figure out how.

Actual test:

Observable.of('')
          .expand(n => n.length < 15 ? Observable.of(n + 'e') : Observable.empty())
          .mergeMap(n => Observable.of(n + 'm'))
          .subscribe(v => console.log(v));

Output:

m
em
eem
eeem
eeeem
eeeeem

Expected output:

em
emem
ememem

The goal of this is to add informations to each expand call using an http request.

Upvotes: 2

Views: 673

Answers (1)

cartant
cartant

Reputation: 58400

The function passed to expand receives the value that's emitted by expand. It doesn't receive the value that's emitted by the entire chain.

So if you want the added information (m) to be included in the value passed to said function, the mergeMap will have to be composed inside expand:

Rx.Observable.of('').expand(n => n.length < 15 ?
    Rx.Observable.of(n + 'e').mergeMap(n => Rx.Observable.of(n + 'm')) :
    Rx.Observable.empty()
)
.subscribe(v => console.log(v));
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://unpkg.com/rxjs@5/bundles/Rx.min.js"></script>

Upvotes: 1

Related Questions