kitimenpolku
kitimenpolku

Reputation: 2604

RxJS - FlatMap observer called multiple times

I'm trying to understand how flatMap works. I understand that it is a way for handling Observable< Observable < T>>.

Anyhow, I was testing the behaviour of it and got stuck with this:

let plusDom = document.querySelector('#plus');
let minusDom = document.querySelector('#minus');

let minusSource = Rx
              .Observable
              .fromEvent(minusDom, 'click');

let plusSource = Rx.Observable
  .fromEvent(plusDom, 'click');

plusSource
  .flatMap(function(c){
    console.log('Flatmap called');
    return minusSource;
  })
  .subscribe(function(e){
  console.log('done');
})

Here it is the jsbin: https://jsbin.com/sefoyowuqe/edit?html,js,console,output

I don't understand this behaviour:

3 clicks on plusDom prints:
Flatmap called
Flatmap called
Flatmap called

1 click on minusDom prints:

done
done
done

Why when clicking the minusDom it replays the events as many times as we have click the plusDom?

Upvotes: 5

Views: 1292

Answers (1)

Olaf Horstmann
Olaf Horstmann

Reputation: 16882

flatMap basically places the returned stream flat into the original stream. What you are probably looking for is switchMap, which will switch to that returned stream and switch to a new stream when the original source emits data by discarding the old one.

When in doubt, switchMap is usually the safest alternative to use.

See the marble-diagrams for comparison:

Flatmap doesn't remove previously "flattened" streams and :

flatMap Marble Diagram

Switchmap removes previously "switched" streams.

switchMap Marble Diagram

Upvotes: 3

Related Questions